About the Developer's Reference

 welcome to Mathcad Developer's Reference

Welcome to the Developer's Reference. These pages are designed to help you, the advanced Mathcad user, customize Mathcad for use as an integral component of your engineering, business, and applied math solutions. This reference assumes that you are familiar with a supported scripting language, such as VBScript or JScript. You will find information regarding Scriptable Object components, including customized scripted objects that come preloaded in Mathcad, Mathcad's Object Model, and OLE Automation. Topics include:

  • Information for creating a user DLL.

  • Classes, methods, properties, and events associated with the Data Acquisition control (DAC).

  • Methods, properties, and events associated with Mathsoft Controls.

  • Methods, properties, and events exposed for scripts written with the Scriptable Object component, including script examples.

  • Methods and sample scripts for accessing Mathcad from within other applications that support OLE Automation.

  • Information for using the Mathcad Component Wizard.

For convenience, script examples in each section use VBScript style syntax unless otherwise noted. For sample worksheets that demonstrate use of customized scripted objects, see the SAMPLES directory of your Mathcad installation.


Introduction to Creating a User DLL

Extend Mathcad's power by writing your own customized functions. Your functions will have the same advanced features as Mathcad built-in functions, such as customized error messages, interruption, and exception handling in case of overflow and divide by zero. Your functions will appear in the Insert Function dialog box like all built-in functions. The functions may operate on complex scalars, complex arrays, and strings and they may return complex scalars, complex arrays, strings, and error messages.

This section describes how to create 32-bit DLLs for Mathcad. The following topics make up this section:

Creating dynamically linked libraries

An overview of how to write your function and fill out the FUNCTIONINFO structure.

A sample DLL

A simple example of a user-created DLL with extensive comments. This sample can be used as a template for your own DLL.

Examining a sample DLL

A detailed examination of a simple example DLL, explaining the COMPLEXARRAY and COMPLEXSCALAR structures, error handling and function registration.

Handling arrays

Using the COMPLEXARRAY structure to handle arrays.

Allocating memory

Allocating and freeing memory.

Exception handling

How Mathcad traps the floating point exceptions.

Structure and function definitions

A reference guide to the structures and functions used.


Creating Dynamically Linked Libraries

To create customized functions, you will first need to create source code in C or C++, then compile the source code with a 32-bit compiler. Next, you will link the object files together with the MathSoft-provided MCADUSER.LIB library to create a DLL. Finally, you will place your DLL into the USEREFI subdirectory and add an entry to USER.XML so that your function appears in the Insert Function dialog box.


Writing your DLL Source Code

Provided below is an overview of the steps involved in creating a DLL. Refer to the rest of this appendix for specific details on how to perform each step.

Writing a DLL entry point routine

When you start Mathcad, it looks in the USEREFI directory for library files with a DLL extension. Mathcad then attempts to load all such files. During the loading process, your DLL must supply Mathcad with information about your library, including the names of the functions in the library, the types of arguments the functions take, the types of values they return, and the text of possible error messages. To supply this information, your DLL must have an entry point routine. A DLL entry point routine is called by the operating system when the DLL is loaded. Because the way to specify the DLL entry point routine is linker specific, refer to the README.TXT file in the compiler specific subdirectory of the USEREFI directory for linking instructions.

Registering your function

For each function in your library, there must be a FUNCTIONINFO structure. The FUNCTIONINFO structure contains the information that Mathcad uses to register a user function. FUNCTIONINFO structure is an argument of CreateUserFunction. A call to CreateUserFunction inside the DLL entry point routine registers your function with Mathcad.

Writing your function

You must, of course, write a C or C++ code that implements your Mathcad user function. The parameters of your C/C++ function are pointers to the return value and to the arguments. The C/C++ function returns 0 if successful, otherwise it returns an error code. The address of the C/C++ function is passed to Mathcad inside a FUNCTIONINFO structure. In this way, Mathcad knows to execute your code when the function is called from a Mathcad document. Refer to MyCFunction.

Error Handling

C/C++ functions which return error messages require an error message table in the DLL code. A call to CreateUserErrorMessageTable inside the DLL entry point routine informs Mathcad of the meaning of error codes returned by the C/C++ functions in the DLL.


Compiling and Linking your DLL

To create your DLL you will need a 32-bit compiler such as Microsoft Visual C++ 5.0, Borland C++ version 5.0, or Watcom C++ version 11.0 (of course, more recent versions of any of these compilers will work as well). Instructions on compiling and linking your DLL are given in the README.TXT file in the compiler specific subdirectory of the USEREFI directory. For more specific instructions on how to link and compile your source code, refer to the user guide provided with your compiler.


Making the Function Available through the Insert Function Box

Making the Function Available

In order to make a function appear in the Insert Function dialog box, you must provide information in the file USER.XML located in the \DOC\FUNCDOC subdirectory. Each function is an entry between <function> tag. Use the <name>, <category>, and <description> tags to specify the function name, its category, and its description as they should appear in the Insert Function dialog box. Between the <params> tag, indicate the parameters the function accepts. If you create a CHM Help file for your functions, use the <help_file> tag at the top of the XML file to provide the CHM filename. Use the <help_topic> tag between the <function> tag to specify the name of a help topic for a function.

See Providing Information for the Insert Function Dialog Box for a sample function entry.

Note:

  • Since Mathcad function names are case-sensitive, be careful to use the proper case when specifying the function name in USER.XML.


A Sample DLL

To get you started writing DLLs for Mathcad a number of code samples are included. The example given in the Sample Code topic is the file MULTIPLY.C located in the USEREFI\MICROSOFT\SOURCES\SIMPLE subdirectory.

The file contains a function that returns the result of multiplying an array by a scalar. This code implements the Mathcad user function multiply(a, M), which returns the result of an array M multiplied by a scalar a. For a complete examination of the source code, see Examining a Sample DLL.


Sample Code

#include "mcadincl.h"

#define INTERRUPTED 1
#define INSUFFICIENT_MEMORY 2
#define MUST_BE_REAL 3
#define NUMBER_OF_ERRORS 3

// tool tip error messages
// if your function never returns an error, you do not need to create this table
char * myErrorMessageTable[NUMBER_OF_ERRORS] =
{

"interrupted",.
"insufficient memory",
"must be real"

};

// this code executes the multiplication
// see the information on MyCFunction to find out more
LRESULT MultiplyRealArrayByRealScalar(

COMPLEXARRAY * const Product,
const COMPLEXSCALAR * const Scalar,
const COMPLEXARRAY * const Array )

{

unsigned int row, col;
// check that the scalar argument is real
if ( Scalar->imag != 0.0)

// if not, display “must be real” under scalar argument
return MAKELRESULT( MUST_BE_REAL, 1 );

// check that the array argument is real
if ( Array->hImag != NULL )

// if not, display “must be real” under array argument
return MAKELRESULT( MUST_BE_REAL, 2 );

// allocate memory for the product
if( !MathcadArrayAllocate( Product, Array-rows,Array-cols,

// allocate memory for the real part
TRUE,

// do not allocate memory for the imaginary part
FALSE ))&#9;

// if allocation is not successful, return with the appropriate error code
return INSUFFICIENT_MEMORY;

// if all is well so far, perform the multiplication
for ( col = 0; col < Product-> cols; col++ )
{

// check that a user has not tried to interrupt the calculation
if ( isUserInterrupted() )
{

// if user has interrupted, free the allocated memory
MathcadArrayFree( Product );

// and return with an appropriate error
 code
return INTERRUPTED;
}
for ( row = 0; row < Product-> rows; row++ )

Product->hReal[col][row] =

Scalar-> real*Array-> hReal[col][row];

}

// normal return
return 0;

}
// fill out a FunctionInfo structure with
// the information needed for registering the function with Mathcad
FUNCTIONINFO multiply =
{
// name by which Mathcad will recognize the function
"multiply",

// description of “multiply” parameters
"a,M",

// description of the function
"returns the product of real scalar a and real array M",

// pointer to the executable code
// i.e. code that should be executed when a user types in “multiply(a,M)=”
(LPCFUNCTION)MultiplyRealArrayByRealScalar;

// multiply(a, M) returns a complex array
COMPLEX_ARRAY,

// multiply(a, M) takes on two arguments
2,

// the first is a complex scalar, the second a complex array
{ COMPLEX_SCALAR, COMPLEX_ARRAY}
};

// all Mathcad DLLs must have a DLL entry point code
// the _CRT_INIT function is needed if you are using Microsoft's 32-bit compiler
BOOL WINAPI _CRT_INIT(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved);
BOOL WINAPI DllEntryPoint (HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved)
{

switch (dwReason)
{

case DLL_PROCESS_ATTACH:

// DLL is attaching to the address space of the current process.
// the next two lines are Microsoft-specific
if (!_CRT_INIT(hDLL, dwReason, lpReserved))

return FALSE;

// register the error message table
// if your function never returns an error,
// you don't need to register an error message table
if ( CreateUserErrorMessageTable( hDLL,

NUMBER_OF_ERRORS, myErrorMessageTable ) )
// and if the errors register OK, register the user function
CreateUserFunction( hDLL, &multiply );

break;

case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:

// the next two lines are Microsoft-specific
if (!_CRT_INIT(hDLL, dwReason, lpReserved))

return FALSE;

break;

}
return TRUE;

}

#undef INTERRUPTED
#undef INSUFFICIENT_MEMORY
#undef MUST_BE_REAL
#undef NUMBER_OF_ERRORS


Compiling and Linking the Sample DLL

If you are using a Microsoft 32-bit compiler you can compile this file with the following command

cl -c -I..\..\include -DWIN32 multiply.c

This creates an object file MULTIPLY.OBJ. You can use the following command to link MULTIPLY.OBJ with the appropriate library and place MULTIPLY.DLL in the USEREFI directory.

link -out:..\..\..\multiply.dll -dll
-entry:"DllEntryPoint" multiply.obj
..\..\lib\mcaduser.lib

Check to make sure the MULTIPLY.DLL file is in the USEREFI subdirectory.


Providing Information for the Insert Function Dialog Box

In order to make the function and its description appear in the Insert Function dialog box, you must provide information in the file USER.XML, located in the \DOC\FUNCDOC subdirectory. You can edit the XML file using a simple text editor such as Notepad or Wordpad. For this function, you can enter the following:

<function>
<name>
multiply
</name>
<params>
a, M
</params>
<category>
User defined
</category>
<description>
Returns the product of real scalar a and real array M
</description>
</function>

Save the file. Start Mathcad and verify that multiply appears in the Insert Function dialog box. You are now ready to use multiply in Mathcad.

Notes:

  • If you can create compiled Help (*.chm) files, you can also use the help_topic tag to link to additional documentation on your function. Mathcad only allows you to specify one Help file per XML file, so if you have multiple chm files, you should group your functions by the Help file that references them.

  • The params tag controls how many placeholders are included when you insert your function.

  • Since you are writing an XML file, you must remember to use closing tags. Failure to do so may cause problems when you access the function in the Insert Function dialog box.


Examining a Sample DLL

This section will examine the source code of the simple example in the previous section. Refer to the source code in the Sample DLL topic. Topics are as follows:

MyCFunction

COMPLEXSCALAR Structure

COMPLEXARRAY Structure

Error Messages

DLL Entry Point Function

FUNCTIONINFO Structure

Precision

mcadincl.h


MyCFunction

The heart of the program is MyCFunction, called MultiplyRealArrayByRealScalar function. It performs the actual multiplication. When the user types multiply(a,M)=, Mathcad executes the MultiplyRealArrayByRealScalar routine. The value of a is passed to the MultiplyRealArrayByRealScalar function in the Scalar argument. The value of M is passed in the Array argument. A pointer to the return value Product is the first argument of the MultiplyRealArrayByRealScalar function.


COMPLEXSCALAR Structure

The scalar value a is passed to the MultiplyRealArrayByRealScalar function in a COMPLEXSCALAR structure. The structure has two members, real and imag. The real part of a is stored in ScalarÞreal, the imaginary part in ScalarÞimag.


COMPLEXARRAY Structure

The array value M is passed to the MultiplyRealArrayByRealScalar function in a COMPLEXARRAY structure. The COMPLEXARRAY structure has four members, rows, cols, hReal, and hImag. The number of rows in M is found in ArrayÞrows, the number of columns is found in ArrayÞcols. The real part of the element Mrow,col is found in ArrayÞhReal[col][row] and the imaginary part in ArrayÞhImag[col][row]. If no element of M has an imaginary part, ArrayÞhImag is equal to NULL. If all elements of M are purely imaginary, ArrayÞhReal is equal to NULL.

The result of the multiplication of M by a is stored by the program in the COMPLEXARRAY structure pointed to by the argument Product. Note the memory for the multiplication result is allocated inside the MultiplyRealArrayByRealScalar function with a call to the MathcadArrayAllocate function.


Error Messages

If the multiplication was successful, MultiplyRealArrayByRealScalar stores the result in the COMPLEXARRAY structure pointed to by the argument Product and returns 0. In the case of an error, its return value has two components. One is the error code and the other is the location in which to display the error message.

Look at the error message table from the top of the file:

char * myErrorMessageTable[NUMBER_OF_ERRORS] =
{

"interrupted",
"insufficient memory",
"must be real"

};

The function MultiplyRealArrayByRealScalar returns MAKELRESULT(3,1) to display string number 3, “must be real,” under the first argument of multiply(a,M). If MathcadArrayAllocate is unable to allocate memory, MultiplyRealArrayByRealScalar returns 2 to display string number 2, “insufficient memory,” under the function name.

As shown in the sample DLL code, the following steps are involved in producing an error message:

  • creation of an array of error message strings.

  • registering the error message strings with Mathcad via a call to CreateUserErrorMessageTable. This call is made within the DLL entry point routine.

  • returning an appropriate error code from the user function.


DLL Entry Point Function

The DLL entry point is called by the operating system when the DLL is loaded. Mathcad requires that you register your user functions and your error message table while the DLL is being loaded. Note how this is done in the following code lines.

BOOL WINAPI DllEntryPoint (HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved)
{

switch (dwReason)
{

case DLL_PROCESS_ATTACH:

if ( CreateUserErrorMessageTable( hDLL,

NUMBER_OF_ERRORS, myErrorMessageTable ) )
// if the errors register OK, register user function
CreateUserFunction( hDLL, &multiply );

break;

case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:

break;

}
return TRUE;

}

CreateUserErrorMessageTable registers the error messages. CreateUserFunction registers the function. You can register only one error message table per DLL, but you can register more than one function per DLL.


FUNCTIONINFO Structure

The FUNCTIONINFO structure, multiply, is used for registering the DLL function with Mathcad. It contains information about the name by which Mathcad recognizes the function, the description of the function parameters, its arguments, its return value, and the pointer to the code which executes the function.

FUNCTIONINFO multiply =
{

"multiply",
"a,M",
"returns the product of real scalar a and real array M",
(LPCFUNCTION)MultiplyRealArrayByRealScalar;
COMPLEX_ARRAY,
2,
{COMPLEX_SCALAR, COMPLEX_ARRAY}

};


Precision

Data is passed between Mathcad and MyCFunction in double precision. Use the appropriate conversion inside MyCFunction for different data types.


mcadincl.h

Mathsoft provides the mcadincl.h include file. This file contains the prototypes for the following functions:

CreateUserFunction
CreateUserErrorMessageTable
MathcadAllocate
MathcadFree
MathcadArrayAllocate
MyCFunction
MathcadArrayFree
isUserInterrupted

mcadincl.h also includes the type definitions for the structures COMPLEXSCALAR, COMPLEXARRAY, and FUNCTIONINFO.


Handling Arrays

If your function takes an array as its argument or returns an array, refer to The COMPLEXARRAY Structure. Note that the arrays are two-dimensional and the structure contains information about the size of the arrays and the pointers to the real and imaginary parts of the array. Refer to Allocating Memory for information on how to allocate memory inside COMPLEXARRAY structures.


Allocating Memory

The first argument of MyCFunction is a pointer to a return value. If it points to a COMPLEXARRAY structure, you will need to allocate memory for the members of this structure using MathcadArrayAllocate. If MyCFunction is returning an error, free the memory allocated for the return value using MathcadArrayFree. In the case of an error-free return, do not free the memory allocated for the return value.

Use the MathcadAllocate and MathcadFree functions to allocate and free memory inside MyCFunction.


Exception Handling

Mathcad traps the following floating point exceptions; overflow, divide by zero, and invalid operation. In the case of these exceptions, Mathcad will display a floating point error message under the function. Mathcad will also free all the memory allocated inside MyCFunction with MathcadArrayAllocate and MathcadAllocate.


Structure and Function Definitions

This section describes in more detail the structures and functions used in creating your own dynamically linked library. Topics are as follows:

The COMPLEXSCALAR Structure

The COMPLEXARRAY Structure

The FUNCTIONINFO Structure

CreateUserFunction

CreateUserErrorMessageTable

MathcadAllocate

MathcadFree

MathcadArrayAllocate

My C Function

MathcadArrayFree

isUserInterrupted


The COMPLEXSCALAR Structure

typedef struct tagCOMPLEXSCALAR {

double real;
double imag;

} COMPLEXSCALAR;

The COMPLEXSCALAR structure is used to pass scalar data between Mathcad and a user DLL. The real part of a scalar is stored in the real member of a COMPLEXSCALAR, and the imaginary in the imag member.

Member | Description
real | Contains the real part of a scalar.
imag | Contains the imaginary part of a scalar.


The COMPLEXARRAY Structure

typedef struct tagCOMPLEXARRAY {

unsigned int rows;
unsigned int cols;
double **hReal;
double **hImag;

} COMPLEXARRAY;

The COMPLEXARRAY structure is used to pass array data between Mathcad and a user DLL. It contains the information about the size of the array and whether any of the elements in the array has an imaginary or a real component.

Member | Description
rows | Number of rows in the array.
cols | Number of columns in the array.
hReal | Points to the real part of a complex array hReal[i][j] contains the element in the ith column and the jth row of the array. hReal is equal to NULL if the array has no real component.
hImag | Points to the imaginary part of a complex array hImag[i][j], contains the element in the ith column and the jth row of the array. hImag equals NULL if the array has no imaginary component.

Comments

hReal and hImag members of the argument array are indexed as two-dimensional array of the range [0 .. cols – 1][0 .. rows – 1].


The FUNCTIONINFO Structure

typedef struct tagFUNCTIONINFO{

char * lpstrName;
char * lpstrParameters;
char * lpstrDescription;
LPCFUNCTION lpfnMyCFunction;
long unsigned int returnType;
unsigned int nArgs;
long unsigned int argType[MAX_ARGS];

} FUNCTIONINFO;

The FUNCTIONINFO structure contains the information that Mathcad uses to register a user function. Refer below for each member and its description.

Member | Description
lpstrName | Points to a NULL-terminated string that specifies the name of the user function.
lpstrParameters | Points to a NULL-terminated string that specifies the parameters of the user function. The string is used by the Insert Function dialog box.
lpstrDescription | Points to a NULL-terminated string that specifies the function description for the Insert Function dialog box.
lpfnMyCFunction | Pointer to the code that executes the user function.
returnType | Specifies the type of value returned by the function. The values are COMPLEX_ARRAY or COMPLEX_SCALAR.
nArgs | Specifies the number of arguments expected by the function. Must be between 1 and MAX_ARGS.
argType | Specifies an array of long unsigned integers containing input parameter types.


CreateUserFunction

const void * CreateUserFunction(hDLL, functionInfo)
HINSTANCE hDLL;
FUNCTIONINFO * functionInfo;

CreateUserFunction is called when the DLL is attaching to the address space of the current process in order to register the user function with Mathcad.

Parameter

Description

hDLL

Handle of the DLL supplied by the DLL entry point routine.

functionInfo

Points to the FUNCTIONINFO structure that contains information about the function.
The FUNCTIONINFO structure has the following form:

typedef struct tagFUNCTIONINFO{

char * lpstrName;
char * lpstrParameters;
char * lpstrDescription;
LPCFUNCTION lpfnMyCFunction;
long unsigned int returnType;
unsigned int nArgs;
long unsigned int argType[MAX_ARGS];

} FUNCTIONINFO;

Return value

The return value is a non-NULL handle if the registration is successful. Otherwise, it is NULL.


CreateUserErrorMessageTable

BOOL CreateUserErrorMessageTable(hDLL,n,ErrorMessageTable)
HINSTANCE hDLL;
unsigned int n;
char * ErrorMessageTable[ ];

CreateUserErrorMessageTable is called when the DLL is attaching to the address space of the current process in order to register the user error message table with Mathcad.

Parameter | Description
hDLL | Handle of the DLL supplied by the DLL entry point routine.
n | Number of error messages in the table.
ErrorMessageTable | An array of n strings with the text of the error messages.

Return value

The return value is TRUE if the registration is successful. Otherwise, it is FALSE.


MathcadAllocate

char * MathcadAllocate(size)
unsigned int size;

Should be used to allocate memory inside the MyCFunction. Allocates a memory block of a given size (in bytes) of memory.

Parameter | Description
size | Size (in bytes) of memory block to allocate. Should be non-zero.

Return value

Returns a pointer to the storage space. To get a pointer to a type other than char, use a type cast on the return value. Returns NULL if the allocation failed or if size is equal to 0.


MathcadFree

void MathcadFree(address)
char * address;

Should be used to free memory allocated with MathcadAllocate. The argument address points to the memory previously allocated with MathcadAllocate. A NULL pointer argument is ignored.

Parameter | Description
address | Address of the memory block that is to be freed.

Return value

The function does not return a value.


MathcadArrayAllocate

BOOL MathcadArrayAllocate(array, rows, cols, allocateReal,
allocateImaginary)
COMPLEXARRAY* const array;
unsigned int rows;
unsigned int cols;
BOOL allocateReal;
BOOL allocateImaginary;

Allocates memory for a COMPLEXARRAY of cols columns and rows rows. Sets the hReal, hImag, rows and cols members of the argument array.

Parameter

Description

array

Points to the COMPLEXARRAY structure that is to be filled with the information about an array.

The COMPLEXARRAY structure has the following form:

&#9;typedef struct tagCOMPLEXARRAY {
unsigned int rows;
unsigned int cols;
double **hReal;
double **hImag;
} COMPLEXARRAY;

rows

Row dimension of the array that is being allocated. After a successful allocation, the rows member of the argument array is set to the value of rows.

cols

Column dimension of the array that is being allocated. After a successful allocation, the cols member of the argument array is set to the value of cols.

allocateReal

Boolean flag indicating whether a memory block should be allocated to store the real part of the array. If allocateReal is FALSE the function does not allocate storage for the real part of array and sets the hReal member to NULL.

allocateImag

Boolean flag indicating whether a memory block should be allocated to store the imaginary part of the array. If allocateImag is FALSE the function does not allocate storage for the imaginary part of array and sets the hImag member to NULL.

Return value

Returns TRUE if the allocation is successful, FALSE otherwise.

Comments

hReal and hImag members of the argument array are allocated as 2-dimensional array of the range [0 .. cols – 1][0 .. rows – 1].


My C Function

LRESULT MyCFunction(returnValue, argument1,...)
void * const returnValue;
const void * const argument1;
...

MyCFunction is the actual code which executes the user function. Mathcad arguments and a pointer to a return value are passed to this function. It puts the result of the calculation in the return value.

Parameter | Description
returnValue | Points to a COMPLEXARRAY or a COMPLEXSCALAR structure where the function result is to be stored. If you are implementing a Mathcad user function which returns a scalar, returnValue is a pointer to a COMPLEXSCALAR structure. If you are implementing a Mathcad user function that returns an array, returnValue points to a COMPLEXARRAY structure.
argument1 | Points to a read-only COMPLEXARRAY or a COMPLEXSCALAR structure where the first function argument is stored. If you are implementing a Mathcad user function that has a scalar as its first argument, argument1 is a pointer to a COMPLEXSCALAR structure. If you are implementing a Mathcad user function that has an array as its first argument, argument1 points to a COMPLEXARRAY structure.
... | If you are implementing a Mathcad user function that has more than one argument, your MyCFunction will have additional arguments. The additional arguments will be pointers to the read-only COMPLEXARRAY or a COMPLEXSCALAR structures where the data for the corresponding Mathcad user function argument is stored.

Return value

MyCFunction should return 0 to indicate an error-free return. To indicate an error MyCFunction should return an error code in the low word of the returned LRESULT, and in the high word the number of the argument under which the error box should be placed. If the high word is zero the error message box is placed under the function itself. See the section on error handling to find out more about error codes.

Comments

MyCFunction is a placeholder for the library-supplied function name. You can name the function that executes your Mathcad user function anything you would like, but you must register the address of your executable code with Mathcad by setting the lpfnMyCFunction member of the FUNCTIONINFO structure.


MathcadArrayFree

void MathcadArrayFree(array)
COMPLEXARRAY * const array;

Frees memory that was allocated by the MathcadArrayAllocate function to the hReal and hImag members of the argument array.

Parameter

Description

array

Points to the COMPLEXARRAY structure that is to be filled with the information about an array.
The COMPLEXARRAY structure has the following form:

typedef struct tagCOMPLEXARRAY {

unsigned int rows;
unsigned int cols;
double **hReal;
double **hImag;

} COMPLEXARRAY;

Return value

The function does not return a value.


isUserInterrupted

BOOL isUserInterrupted(void)

The isUserInterrupted function is used to check whether a user has pressed the [Esc] key. Include this function if you want to be able to interrupt your function like other Mathcad functions.

Parameter

The function does not take any parameters.

Return value

Returns TRUE if the[Esc] key has been pressed, FALSE otherwise.


end

Terms of Use

DLL interface specifications contained in this Developer's Reference may be used for creating user-written external functions which work with Mathcad for your personal or internal business use only. These specifications may not be used for creating external functions for commercial resale without the prior written consent of Mathsoft, Inc.


Data Acquisition Control (DAC) Overview

The Mathcad Data Acquisition Control (DAC) is an ActiveX control that allows you to acquire data from and send data to a data acquisition device installed on your computer. Its purpose is to allow a direct connection between Mathcad and any supported data acquisition devices by inserting the control into a Scriptable Object component (SOC). However, it may also be used in other programming environments, for example, in a Visual Basic project or on an Excel spreadsheet.

This help file contains descriptions and code examples for all methods, properties and events associated with the control. The methods, properties and events are organized into individual book chapters.

The properties and methods of the control may be accessed and changed in various ways. You can use the form-like user interface, the properties dialog, or access properties and methods programmatically. The form-like user interface is the easiest way to access the properties and methods if you are using a visible instance of the control.

Minimum Requirements

For the data acquisition control to work you must have NI-DAQ Version 6.7 or higher (National Instruments cards and devices only) and Mathcad 2000 or higher installed. You must, of course, also satisfy the minimum requirements of all required software for them to work properly.

General Overview of Data Acquisition

The Mathcad Data Acquisition Control is an ActiveX control that interacts with any supported data acquisition devices installed on your computer.

The Data Acquisition Component (DAC) is comprised of the data acquisition control embedded in a Scriptable Object component (SOC). The SOC is then saved to a user component MCM file. The user component can be inserted like any other component.

Thus, the DAC is not a native Mathcad component. As such, some scripting must be done to communicate with the embedded control. At a minimum, you must bind inputs and outputs of the SOC to data members of the embedded control.

When the DAC is inserted into a Mathcad worksheet it is set up for the default operation of single point analog input. The control properties can be changed by using the form-like user interface (UI), the Properties dialog, or programmatically. Any subsequent changes you make to the control's properties are saved when you close the Mathcad worksheet. So, the next time you open a worksheet containing a DAC the embedded control will be set up as it last was.

Example worksheets contained in the \Samples\DAC subfolder of the Mathcad installation folder illustrate how to use the DAC for single point and waveform analog input and output. These example files are an excellent starting point for creating your own worksheets.

Basic Operation

The basic operation of the DAC is as follows. You specify the particular operation to be performed and the channels that it will be performed on. The channels are specified using the ChannelString property. When the ChannelString property is set, a Channel object is created for each channel specified. Interaction with the outside world is accomplished through the Data member of each Channel object.

When acquiring data the SOC should automatically recalculate whenever any of its output values change. The embedded control also raises the DataAcquired or DataSent events upon completion of data transfer. These events can be used for event handler routines within the SOC.

When sending data the SOC should pass an input value to the Data member of a Channel object and the Send method should be called in the Exec routine of the SOC. If you don't want to send data automatically when the SOC is recalculated leave the Send method out of the Exec routine and manually click the Send button on the UI.

Use of Triggers

The wait for trigger feature is only applicable for waveform analog input operations.

In order to use the wait for trigger feature your device must support digital or analog triggers. Digital triggers are applied at the PFI0 pin and are TTL transitions from either high-to-low or low-to-high (depending on your device). Analog triggers can be specified at PFI0 or an analog input channel and can be set for either a high-to-low or low-to-high transition and a specific voltage level can set to trigger at. Only the first channel in the channel string may be the analog trigger input.

To eliminate spurious triggers on analog input channels, make sure you read the trigger-related information in your device documentation.

Enabling Controls

As a safeguard against potentially destructive code, Mathcad issues a warning message every time you attempt to open a worksheet that contains scripted objects. If you are opening a worksheet containing scripted objects that you know to be safe, such as the sample files that demonstrate the DAC, simply click "No" when the warning box comes up. This will enable all scripted objects in the worksheet. If you answer "Yes" and still want to enable these components in the worksheet, either right click a single control and select Enable Evaluation from the popup menu, or select one or more controls, right click and select Properties from the popup menu. In the Properties dialog under Calculation, uncheck "Disable Evaluation".

Sample File

Here are four sample files that demonstrate using the DAC in a worksheet.

Launch QuickSheet Example (Single Point Input)

Launch QuickSheet Example (Single Point Output)

Launch QuickSheet Example (Waveform Input)

Launch QuickSheet Example (Waveform Output)


Supported Devices

For the Mathcad Data Acquisition Control to work properly, your data acquisition device must be properly installed in accordance with the instructions provided by the manufacturer.

At this time, the control only supports National Instruments E-Series data acquisition boards and PC cards, and Measurement Computing (formerly ComputerBoards) devices. The control may also work with non-E-Series devices (e.g. the DAQCard-500). The control supports only analog input and output functionality for Measurement Computing devices.


Limitations

Limitations of the Mathcad Data Acquisition Control

  1. The control uses the default settings for the active device, i.e. input polarity and range and the input mode (e.g. referenced single ended, non-referenced single ended, or differential) . To configure the default setting for the devices installed on your computer, use the National Instruments Measurement & Automation Explorer.

  2. The use of AMUX-64T multiplexer devices is not supported at this time.

  3. Before you can access data members of the Channels collection, you must set the ChannelString property.

  4. The analog channel used for analog triggering is always the first channel in the channel string. If you edit the channel string, the order that the channels appear in the Channels collection may not agree with what is typed (e.g. if the channel string was 1:3 and then you edited it to be 0,1,2,3 channel zero would be added to the end of the channels collection and would actually be the fourth item in the collection). To clear the channel string set it equal to a blank string and then specify a new channel string. This will place members into the Channels collection in the order that they appear in the ChannelString.

  5. The values you receive from and send to the active device are in volts.

  6. The control does not implement all possible functions as it is intended to be used with Mathcad. For example, there is no wait for trigger feature for analog output because it is assumed that the results of a Mathcad calculation will trigger the analog output operation.


MDAQ_CHANNEL

MDAQChannel Class

The MDAQChannel class stores information related to all channels in the channel string.

The Channels collection is populated with an MDAQChannel object for each channel in the channel string as a result of any change to the ChannelString property.

The MDAQChannel class members are Variants so that they may be accessed via VBScript and are described as follows:

Member Description

Number As Variant (Integer)

The actual channel number that the object refers to.

Data As Variant (Double)

Stores data related to the data transfer operation. For output, the data values are specified prior to sending data to the device. For input, this member stores the results of the data acquisition. The value is a scalar for single point operations and an array for waveform operations.

AIGain As Variant (Integer)

The analog input gain for the channel.

DeltaT As Variant (Double)

For waveform input or output operations, this value represents the actual time difference in seconds between analog to digital or digital to analog conversions. Usually, this number is the same as the inverse of the sample or update rate. However, if the device could not exactly match the particular rate this number will differ. Always check this value when performing waveform operations to ensure that actual time between samples or updates is known.


MDAQ_DEVICE

MDAQDevice Class

The MDAQDevice class stores information related to all data acquisition devices installed on your computer.

The InstalledDevices collection is populated with an MDAQDevice object for each installed device as a result of a call to the QueryDevices Method. The QueryDevices Method is automatically called when the control is initialized so there should be no need to call it under normal circumstances. However, if you reconfigure devices while an instance of the control is running (e.g. change the device number) the QueryDevices method should be called to update information on the devices.

The MDAQDevice class has these members:

Member Description

Number As Integer

The number assigned to the device by the configuration utility.

DevType As String

The name of the device, e.g. DAQCard-500.

DevTypeCode As Long

The National Instruments device type code.

NumAIChannels As Long

The number of analog input channels that the device supports.

SupportsDIFFAI As Boolean

True if the device supports differential analog input.

SupportsNRSEAI As Boolean

True if the device supports non-referenced single ended analog input.

SupportsRSEAI As Boolean

True if the device supports referenced single ended analog input.

AllowedAIGains As Integer

Specifies the allowed gain values for the device. The values correspond to:

0: 1

1: 1, 10, and 100

2: 1, 2, 10, and 100

3: 1, 2, 5, 10, 20, 50, and 100

ChannelString As String

The channel string for the device.

InputResolution As Integer

The number of bits of resolution for the analog to digital converter.

SupportsAO As Boolean

True if the device supports analog output.

NumAOChannels As Long

The number of analog output channels.

OutputResolution As Integer

The number of bits of resolution for the digital to analog converter.

HasDigTrig As Boolean

True if the device supports digital triggers.

HasAnalogTrig As Boolean

True if the device supports analog triggers.

Supported As Boolean

True if the device is supported by the control.


Acquire

Acquire Method

Reads data from the active data acquisition device.

Syntax

Variant = object.Acquire( )

The Acquire method syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

Remarks

The Acquire method retrieves a reading, in volts, from every channel in the channel string. The data is stored in the Data member of the Channel object. The type of data returned depends on the IOType setting and is a scalar for single point operations and a vector for waveform operations.

The Acquire method returns 0 if successful or -1 if there was an error in at least one of the channels being acquired.

Example

Sub AcquireData()

Dim McadDAQ As AnalogIO

Dim vResult as Variant

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the channel string

McadDAQ.ChannelString = "0,1,3"

'set the IOFunction and IOType to input a single point from every channel in the channel string

McadDAQ.IOFunction = 0

McadDAQ.IOType = 0

'use the Acquire method to get the data

vResult = McadDAQ.Acquire

End Sub


Send

Send Method

Sends data to the active data acquisition device.

Syntax

Variant = object.Send( )

The Send method syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

Remarks

The Send method sends the voltage value associated with a channel to all channels in the channel string. Each channel can have its own voltage value independent of the others. If the IOFunction property is set to send, the voltage values are remembered after the document containing the control is closed.

The data to be sent is stored in the Data member of the Channel object. The type of data sent depends on the IOType setting and is a scalar for single point operations and a vector for waveform operations.

The Send method returns 0 if successful or -1 if there was an error in at least one of the channels having data sent to it.

Example

Sub SendData()

Dim McadDAQ As AnalogIO

Dim vResult as Variant

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the channel string

McadDAQ.ChannelString = "0,1"

'set the IOFunction and IOType to output a single point from every channel

' in the channel string

McadDAQ.IOFunction = 1

McadDAQ.IOType = 0

'set the channel data to send

McadDAQ.Channels("0").Data = 1.5#

McadDAQ.Channels("1").Data = 4.25#

'use the Send method to send the data to the output channels

vResult = McadDAQ.Send

End Sub


QueryDevices

QueryDevices Method

Retrieves information on installed and configured data acquisition devices.

Syntax

Variant = object.QueryDevices( )

The QueryDevices method syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

Remarks

The QueryDevices method is called when the control initializes and looks for installed and confugured data acquisition devices on your computer. The results are stored in the InstalledDevices collection. The QueryDevices method returns 0 if there was at least one supported device installed on your computer and -1 otherwise.

Example

Sub GetDeviceInfo()

Dim McadDAQ As AnalogIO

Dim vResult as Variant

'the next statement assumes there was a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

vResult = McadDAQ.QueryDevices

End Sub


ShowAbout

ShowAbout Method

Shows the about box for the control.

Syntax

object.ShowAbout( )

The ShowAbout method syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

Remarks

The ShowAbout method is useful for determining the version number of the control. The version number of the control can also be determined by navigating to the file "MathcadDAQ.ocx" in Windows Explorer, right-clicking on the file and selecting "Properties", and then clicking on the "Version" tab of the properties dialog.

If you encounter any errors when using this control please notify Mathsoft technical support and provide a complete description of the problem and the version number of the control so that the problem can be logged in our database and fixed in a future release.

Example

Sub ShowAbout()

Dim McadDAQ As AnalogIO

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

McadDAQ.ShowAboutBox

End Sub


ActiveDevice

ActiveDevice Property

Returns or sets the active data acquisition device.

Syntax

Variant = object.ActiveDevice( )

object.ActiveDevice = vNewValue

The ActiveDevice property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Variant (Integer). The number of the device to make the active device.

Remarks

The ActiveDevice property is used to determine or specify the device that will be used for all subsequent operations. The numbers for devices installed on your computer are assigned using the National Instruments Measurement & Automation Explorer. Valid ranges are from 1 to 16 inclusive.

If an invalid number is specified, e.g. a non-existent device or a non-numeric value, the value reverts to a known good value.

Example

Sub SetGetActiveDevice()

Dim McadDAQ As AnalogIO

Dim vResult as Variant

'the next statement assumes there was a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the new active device

McadDAQ.ActiveDevice = 2%

vResult = McadDAQ.ActiveDevice

MsgBox "The ActiveDevice is now: " & CStr(vResult)

End Sub


ChannelString

ChannelString Property

Returns or sets the channels that subsequent operations are performed on.

Syntax

Variant = object.ChannelString( )

object.ChannelString = vNewValue

The ChannelString property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Variant (String). The new channel string.

Remarks

The ChannelString property is used to determine or specify the channels that all subsequent operations will be performed on.

Individual channels are specified using a comma separating the channels, e.g. "1,3,5" for channels 1, 3, and 5.

A continuous range of channels may be specified using a colon to separate the lower and upper bounds, e.g. "0:4" for channels 0, 1, 2, 3, and 4 or "5:2" for channels 5, 4, 3, and 2.

The ChannelString property must be set before any operation can be performed. Upon specifying the ChannelString property members of the Channels collection are created.

Operations are performed on the channels according to their order in the Channels collection.

Example

Sub SetGetChanString()

Dim McadDAQ As AnalogIO

Dim vResult as Variant

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the new channel string

McadDAQ.ChannelString = "0:4"

vResult = McadDAQ.ChannelString

MsgBox "The new ChannelString is: " & Cstr(vResult)

End Sub


InstalledDevices

InstalledDevices Collection

A collection of information on all installed data acquisition devices. Members of the collection are MDAQDevice class objects.

Syntax

Device = object.InstalledDevices( index)

The InstalledDevices collection syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

index Required. A string or integer value representing the device object to return. Specifying a string for index returns information for the device having the same number. Specifying an integer for index returns that item of the collection. A particular device may not necessarily have the same name as its index in the collection.

Device Required. MDAQDevice. A variable used to hold the device member.

Remarks

The InstalledDevices collection is populated when the control is initialized or after a call to the QueryDevices method.

Example

Sub GetDeviceObject()

Dim McadDAQ As AnalogIO

Dim MyDevice as MDAQDevice

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'get the information for device 1

Set MyDevice = McadDAQ.InstalledDevices("1")

If MyDevice.HasDigTrig Then

MsgBox "Device 1 supports digital triggers"

Else

MsgBox "Device 1 does not support digital triggers"

End If

End Sub


IOType

IOType Property

Returns or sets type of operation the data acquisition device will perform.

Syntax

Variant = object.IOType( )

object.IOType = vNewValue

The IOType property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Variant (Integer). The type of operation to perform. Set to 0 for single point and 1 for waveform.

Remarks

The IOType property is used to determine or specify the type of operation the active device will perform. Valid values for the new value are 0 for single point and 1 for waveform.

Single point operations send or receive a single point of data to or from all channels in the ChannelString.

Waveform input operations acquire the same number of data points from all channels in the ChannelString. Waveform output is only sent to the first analog output channel in the channel string.

For input operations you must specify the Rate and NumSamples properties (or use their default values). For output operation you must specify the Rate and the NumIterations properties (or use their default values) and the number of samples is determined from the size of the data in the channels Data member.

Example

Sub SetGetIOType()

Dim McadDAQ As AnalogIO

Dim vResult as Variant

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the new active device

McadDAQ.IOType = 1%

vResult = McadDAQ.IOType

MsgBox "The IOType is now: " & CStr(vResult)

End Sub


IOFunction

IOFunction Property

Returns or sets function of the data acquisition device.

Syntax

Variant = object.IOFunction( )

object.IOFunction = vNewValue

The IOFunction property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Variant (Integer). The function to perform. Set to 0 for analog input and 1 for analog output.

Remarks

The IOFunction property is used to determine or specify the function of the active device. Valid values for the new value are 0 for analog input and 1 for analog output.

Example

Sub SetGetIOFunction()

Dim McadDAQ As AnalogIO

Dim vResult as Variant

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the new active device

McadDAQ.IOFunction = 0%

vResult = McadDAQ.IOFunction

MsgBox "The IOFunction is now: " & CStr(vResult)

End Sub


Channels Collection

Returns a collection containing MDAQChannel members.

Syntax

Channel = object.Channels(index)

The Channels collection syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

index Required. A string or integer value representing the channel object to return. Specifying a string for index returns information for the channel having the same name. Specifying an integer for index returns that item of the collection.

Channel Required. MDAQChannel. A variable used to store the collection member.

Remarks

The Channels collection is composed of MDAQChannel class objects. The collection is accessed to set or retrieve data for the particular operation. If a non-existent channel index is specified a VB run time error occurs.

Example

Sub GetChannelObject()

Dim McadDAQ As AnalogIO

Dim MyChannel as MDAQChannel

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'get the information for channel 0

Set MyChannel = McadDAQ.Channels("0")

If IsArray(MyChannel.Data) Then

MsgBox "Channel 0 contains array data"

Else

MsgBox "Channel 0 contains scalar data"

End If

End Sub


NumSamples

NumSamples Property

Returns or sets the number of samples to retrieve during waveform acquisition.

Syntax

Variant = object.NumSamples()

object.NumSamples = vNewValue

The NumSamples property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Required. Variant (Integer). The number of samples to acquire.

Remarks

During waveform data acquisition NumSamples of data points are acquired form each channel in the channel string.

Example

Sub GetWaveform()

Dim McadDAQ As AnalogIO

Dim lTemp as Long

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the channel string to acquire from channels 0 and 3

McadDAQ.ChannelString = "0,3"

'set the IOFunction to input

McadDAQ.IOFunction = 0&

'set the IOType to waveform

McadDAQ.IOType = 1&

'set the number of samples to acquire for all channels

McadDAQ.NumSamples = 1000%

'set the sample rate

McadDAQ.Rate = 10000%

'acuire the data

McadDAQ.Acquire

'See if the right number of samples was acquired

lTemp = UBound(McadDAQ.Channels("0").Data) + 1

MsgBox CStr(lTemp) & " samples were acquired"

End Sub


WaitForTrigger

WaitForTrigger Property

Returns or sets a variable that tells the control whether or not to wait for a trigger before starting waveform acquisition.

Syntax

Variant = object.WaitForTrigger()

object.WaitForTrigger = vNewValue

The WaitForTrigger property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Required. Variant (Integer). Set to 1 to wait for a trigger or 0 for not to wait.

Remarks

The WaitForTrigger property, as its name implies, tells the control whether or not to wait for a trigger before starting waveform acquisition. You must specify the trigger properties using the TriggerType, TriggerEdge, TriggerSource, and TriggerLevel properties as appropriate. The default trigger is a digital trigger at the PFI0 pin.

If an invalid value, e.g. other than 0 or 1 or non-numeric, is specified for the property it will default back to 0.

Example

Sub GetWaveformOnTrigger()

Dim McadDAQ As AnalogIO

Dim lTemp as Long

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the channel string to acquire from channel 1

McadDAQ.ChannelString = "1"

'set the IOFunction to input

McadDAQ.IOFunction = 0&

'set the IOType to waveform

McadDAQ.IOType = 1&

'set the number of samples to acquire for all channels

McadDAQ.NumSamples = 1000%

'set the sample rate in samples per second

McadDAQ.Rate = 10000%

'set trigger related information

McadDAQ.WaitForTrigger = 1%

'Set up for low-to-high analog trigger of 2.5 Volts at the PFI0 pin

McadDAQ.TriggerType = 1%

McadDAQ.TriggerSource = 0&

McadDAQ.TriggerEdge = 0&

McadDAQ.TriggerLevel = 2.5#

'acquire the data

McadDAQ.Acquire

'See if the right number of samples was acquired, zero base assumed

On Error Resume Next

lTemp = UBound(McadDAQ.Channels("1").Data) + 1

If Err.Number = 0 Then

MsgBox CStr(lTemp) & " samples were acquired"

Else

MsgBox "Acquisition Error"

End If

End Sub


ShowErrors

ShowErrors Property

Returns or sets a variable that tells the control whether or not to generate NI-DAQ error messages.

Syntax

Variant = object.ShowErrors()

object.ShowErrors = vNewValue

The ShowErrors property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Required. Variant (Integer). Set to 1 to show or 0 for not to show NI-DAQ error messages.

Remarks

If the ShowErrors property is set to 0, no error messages will be generated if inappropriate properties are specified for the active device, for example specifying an out of range channel number in the channel string. This is done so as not to interrupt calculation flow in Mathcad.

If you think all properties are specified correctly for the particular operation being performed but nothing is happening, set the ShowErrors property to 1 and try the operation again.

Example

Sub SetShowErrors()

Dim McadDAQ As AnalogIO

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the ShowErrors property

McadDAQ.ShowErrors = 1%

End Sub


SampleRate

Rate Property

Returns or sets the rate, in samples per second, at which analog to digital or digital to analog conversions take place.

Syntax

Variant = object.Rate()

object.Rate = vNewValue

The Rate property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Required. Variant (Double). The new sample or transfer rate.

Remarks

The Rate property has dual usage. For input operations it specifies the rate at which analog to digital conversions take place. For output operations it specifies the rate at which digital to analog conversions take place.

The time between samples or updates, in seconds, is usually the inverse of the Rate property. However, this may not always be the case. To determine the actual time between samples that was used for the data transfer operation, get the DeltaT property of the channel item.

Example

Sub GetWaveform()

Dim McadDAQ As AnalogIO

Dim lTemp as Long

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the channel string to acquire from channels 0 and 3

McadDAQ.ChannelString = "0,3"

'set the IOFunction to input

McadDAQ.IOFunction = 0&

'set the IOType to waveform

McadDAQ.IOType = 1&

'set the number of samples to acquire for all channels

McadDAQ.NumSamples = 1000%

'set the sample rate in samples per second

McadDAQ.Rate = 10000%

'acuire the data

McadDAQ.Acquire

'See if the right number of samples was acquired, zero base assumed

lTemp = UBound(McadDAQ.Channels("0").Data) + 1

MsgBox CStr(lTemp) & " samples were acquired"

End Sub


NumIterations

NumIterations Property

Returns or sets the number of times to repeat a waveform output.

Syntax

Variant = object.NumIterations()

object.NumIterations = vNewValue

The NumIterations property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Required. Variant (Integer). The number of times to repeat a waveform output.

Remarks

During waveform data output NumIterations of the waveform are sent to the output channel. The minimum value is one. This property is useful for generating a waveform for a long time. For example, instead of generating one thousand cycles of a sine wave, you could generate one cycle and repeat it one thousand times. The latter method can be done specifying less data points.

Example

Sub SendWaveform()

Dim McadDAQ As AnalogIO

Dim i as Integer

Dim vData(99) as Variant

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the channel string to send to channel 0

'Note: you can only send waveform data to one channel

McadDAQ.ChannelString = "0"

'set the IOFunction to output

McadDAQ.IOFunction = 1&

'set the IOType to waveform

McadDAQ.IOType = 1&

'Generate the data to send to the output channel

For i = 0 To 99

vData(i) = sin(i * 2 * 3.14159/100)

Next

'set the channel data

McadDAQ.Channels("0").Data = vData

'set the number of iterations

McadDAQ.NumIterations = 9%

'set the update rate

McadDAQ.Rate = 100%

'generate the waveform

McadDAQ.Send

End Sub


TrigEdge

TriggerEdge Property

Returns or sets the trigger edge transition for analog trigger operations.

Syntax

Variant = object.TriggerEdge()

object.TriggerEdge = vNewValue

The TriggerEdge property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Required. Variant (Long). Set to 0 for low-to-high transition or 1 for high-to-low transition.

Remarks

The TriggerEdge property is used in conjunction with the TriggerLevel property for analog trigger operations and is ignored for digital triggers.

If an invalid value, e.g. other than 0 or 1 or non-numeric, is specified for the property it will default back to 0.

Example

Sub GetWaveformOnTrigger()

Dim McadDAQ As AnalogIO

Dim lTemp as Long

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the channel string to acquire from channel 1

McadDAQ.ChannelString = "1"

'set the IOFunction to input

McadDAQ.IOFunction = 0&

'set the IOType to waveform

McadDAQ.IOType = 1&

'set the number of samples to acquire for all channels

McadDAQ.NumSamples = 1000%

'set the sample rate in samples per second

McadDAQ.Rate = 10000%

'set trigger related information

McadDAQ.WaitForTrigger = 1%

'Set up for low-to-high analog trigger of 2.5 Volts at the PFI0 pin

McadDAQ.TriggerType = 1%

McadDAQ.TriggerSource = 0&

McadDAQ.TriggerEdge = 0&

McadDAQ.TriggerLevel = 2.5#

'acquire the data

McadDAQ.Acquire

'See if the right number of samples was acquired, zero base assumed

On Error Resume Next

lTemp = UBound(McadDAQ.Channels("1").Data) + 1

If Err.Number = 0 Then

MsgBox CStr(lTemp) & " samples were acquired"

Else

MsgBox "Acquisition Error"

End If

End Sub


TrigLevel

TriggerLevel Property

Returns or sets the analog trigger level.

Syntax

Variant = object.TriggerLevel()

object.TriggerLevel = vNewValue

The TriggerLevel property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Required. Variant (Double). The analog trigger level in volts.

Remarks

The TriggerLevel property is used to specify the level of the analog trigger.

If an invalid value, e.g. non-numeric, is specified for the property it will default to 0 volts.

Example

Sub GetWaveformOnTrigger()

Dim McadDAQ As AnalogIO

Dim lTemp as Long

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the channel string to acquire from channel 1

McadDAQ.ChannelString = "1"

'set the IOFunction to input

McadDAQ.IOFunction = 0&

'set the IOType to waveform

McadDAQ.IOType = 1&

'set the number of samples to acquire for all channels

McadDAQ.NumSamples = 1000%

'set the sample rate in samples per second

McadDAQ.Rate = 10000%

'set trigger related information

McadDAQ.WaitForTrigger = 1%

'Set up for low-to-high analog trigger of 2.5 Volts at the PFI0 pin

McadDAQ.TriggerType = 1%

McadDAQ.TriggerSource = 0&

McadDAQ.TriggerEdge = 0&

McadDAQ.TriggerLevel = 2.5#

'acquire the data

McadDAQ.Acquire

'See if the right number of samples was acquired, zero base assumed

On Error Resume Next

lTemp = UBound(McadDAQ.Channels("1").Data) + 1

If Err.Number = 0 Then

MsgBox CStr(lTemp) & " samples were acquired"

Else

MsgBox "Acquisition Error"

End If

End Sub


TrigSource

TriggerSource Property

Returns or sets the trigger source.

Syntax

Variant = object.TriggerSource()

object.TriggerSource = vNewValue

The TriggerSource property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Required. Variant (Long). Set to 0 for PFI0 or 1 for the analog input channel.

Remarks

The TriggerSource property is used to specify the source of the analog trigger. Digital triggers always use the PFI0 pin for the trigger input. If the TriggerType is analog then you can specify that either PFI0 pin or the analog input channel be the source of the trigger. Analog triggers also require that the TriggerLevel and TriggerEdge properties be specified.

If the analog input channel is the source of the trigger and there are multiple channels in the channel string, the first channel in the channels collection is the source of the trigger.

If an invalid value, e.g. other than 0 or 1 or non-numeric, is specified for the property it will default back to 0.

Example

Sub GetWaveformOnTrigger()

Dim McadDAQ As AnalogIO

Dim lTemp as Long

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the channel string to acquire from channel 1

McadDAQ.ChannelString = "1"

'set the IOFunction to input

McadDAQ.IOFunction = 0&

'set the IOType to waveform

McadDAQ.IOType = 1&

'set the number of samples to acquire for all channels

McadDAQ.NumSamples = 1000%

'set the sample rate in samples per second

McadDAQ.Rate = 10000%

'set trigger related information

McadDAQ.WaitForTrigger = 1%

'Set up for low-to-high analog trigger of 2.5 Volts at the PFI0 pin

McadDAQ.TriggerType = 1%

McadDAQ.TriggerSource = 0&

McadDAQ.TriggerEdge = 0&

McadDAQ.TriggerLevel = 2.5#

'acquire the data

McadDAQ.Acquire

'See if the right number of samples was acquired, zero base assumed

On Error Resume Next

lTemp = UBound(McadDAQ.Channels("1").Data) + 1

If Err.Number = 0 Then

MsgBox CStr(lTemp) & " samples were acquired"

Else

MsgBox "Acquisition Error"

End If

End Sub


TrigType

TriggerType Property

Returns or sets the type of trigger to be used.

Syntax

Variant = object.TriggerType()

object.TriggerType = vNewValue

The TriggerType property syntax has these parts:

Part Description

object Required. A valid Mathcad Data Acquisition Control object.

vNewValue Required. Variant (Integer). Set to 0 for digital or 1 for analog.

Remarks

The TriggerType property specifies if digital or analog triggers are to be used. If analog trigger is specified the the TriggerType, TriggerEdge, TriggerSource, and TriggerLevel properties should also be specified as appropriate.

If an invalid value, e.g. other than 0 or 1 or non-numeric, is specified for the property it will default back to 0.

Example

Sub GetWaveformOnDigitalTrigger()

Dim McadDAQ As AnalogIO

Dim lTemp as Long

'the next statement assumes there is a Mathcad Data Acquisition control called

' AnalogIO1 on Form1 of a VisualBasic project

Set McadDAQ = Form1.AnalogIO1

'set the channel string to acquire from channel 1

McadDAQ.ChannelString = "1"

'set the IOFunction to input

McadDAQ.IOFunction = 0&

'set the IOType to waveform

McadDAQ.IOType = 1&

'set the number of samples to acquire for all channels

McadDAQ.NumSamples = 1000%

'set the sample rate in samples per second

McadDAQ.Rate = 10000%

'set trigger related information

McadDAQ.WaitForTrigger = 1%

'Set up for digital trigger at the PFI0 pin

McadDAQ.TriggerType = 0%

'acquire the data

McadDAQ.Acquire

'See if the right number of samples was acquired, zero base assumed

On Error Resume Next

lTemp = UBound(McadDAQ.Channels("1").Data) + 1

If Err.Number = 0 Then

MsgBox CStr(lTemp) & " samples were acquired"

Else

MsgBox "Acquisition Error"

End If

End Sub


DataAcquired

DataAcquired Event

This event is raised after all data for the specified operation has been acquired from the active device.

The purpose of the event is to allow for an event handler routine.


DataSent

DataSent Event

This event is raised after all data for the specified operation has been sent to the active device.

The purpose of the event is to allow for an event handler routine.


Overview of Mathsoft Controls

Mathsoft Controls

Overview

Controls such as list boxes, sliders, and buttons, allow you to create alternate means of entering information into a worksheet other than the standard variable mechanism. This is particularly useful if the end user is new to Mathcad or if you want to streamline an oft-repeated process. Controls are also useful for expanding the degree to which worksheets can be used as templates for processes. For example, a set of controls at the beginning of or throughout a document allows the user to specify quickly and easily various parameters used to compute a series of calculations. In this way, controls further facilitate your design of a solution rather than just a worksheet.

The Mathsoft Controls provide several different user interfaces for entering and displaying data in the worksheet. You can also use controls to get feedback about processes in the worksheet, such as verifying an entry made by the end user. There are four types of controls: buttons, text boxes, list boxes, and sliders. Additionally, buttons come in three varieties: push buttons, radio buttons, and check boxes. Here are a few examples of how controls might be used:

  • You can use a button, check box, or radio button to set a binary state (yes or no, true or false, on or off).

  • You can use list box to allow the end user to choose from among a set of conditions (variable names or values, states of a set of variables, descriptions of scenarios).

  • You can use a slider to control the value of a variable in the worksheet (a parameter of a function, for example).

  • You can use a text box to allow the end user to enter a string (name, description, or type) or to display a string as feedback for an action performed by the user in the worksheet

  • You can use a radio button group or groups and a button together to allow the end user to make a choice or choices and then verify their validity (quiz or survey)

The Scriptable Object Component and MCM Files

Each Mathsoft Control is comprised of an ActiveX User Interface input element embedded in a Scriptable Object component (SOC). The SOC is then saved to a user component MCM file. The user component then appears on the Component list in Mathcad, as well as in the Controls submenu on the Insert menu, and can be inserted in a worksheet like any other component.

Thus, these controls are not native Mathcad components. As such, some scripting must be done to communicate with the embedded element. At a minimum, you must accept the default script of the control, which generally consists of taking user input and returning integer or string output. The default script is written in VBScript. However, if you are interested in scripting these objects from scratch using either VBScript or Jscript, you can use the Scriptable Object component and pick a Mathsoft control from the object list.

Further Customizing the Controls

This help file contains descriptions and code examples for all methods, properties and events associated with the Mathsoft Controls. The methods, properties and events are organized into individual book chapters.

The properties and methods of the control may be accessed and changed using the Properties dialog or programmatically through the script. For certain controls, however, only some properties are accessible in the script. For example, all of the font properties for text boxes must be modified through the Properties dialog.

Inputs and Outputs

The default setting for all controls is one output and no inputs. Therefore, the control responds to user input and generates output based on it. If you are interested in having input from a worksheet variable used in a control, you must add an Input Variable to the control. To do so, right click the control and select Add Input Variable from the popup menu. Likewise, if you are interested in generating more than one output, you must add an Output Variable to the control. Indexing of these variables starts at 0; inputs and outputs may be of any Mathcad supported data type including numbers, arrays, and strings.

Hiding Arguments

It will often be the case that you want to hide from the end user the arguments (inputs and outputs) to a control. To do so, right click the control and select Hide Arguments from the popup menu. To reveal the arguments, right click the control again and select Show Arguments from the popup menu.

Examples

Example worksheets contained in the \qsheet\Samples\Controls folder of your installation of Mathcad illustrate how to use the controls in a variety of ways. In addition to the examples provided in these Help pages, these sample files are an excellent starting point for creating your own controls.

Enabling Controls

As a safeguard against potentially destructive code, Mathcad issues a warning message every time you attempt to open a worksheet that contains scripted objects. If you are opening a worksheet containing scripted objects that you know to be safe, such as the sample files that demonstrate these controls, simply click "No" when the warning box comes up. This will enable all the scripted objects in the worksheet. If you answer "Yes" and still want to enable these components in the worksheet, either right click a single control and select Enable Evaluation from the popup menu, or select one or more controls, right click and select Properties from the popup menu. In the Properties dialog under Calculation, uncheck "Disable Evaluation".


Overview of Text Boxes

Mathsoft TextBox Control

Overview

The Mathsoft TextBox Control allows you to accept user input in the form of text, which can then be used as string or number data for calculations. You can change the appearance of a text box using the Properties dialog box or access its properties through the script. Descriptions and code examples for all properties are given in the Help pages that follow.

Simple Annotated Example

Here’s an example that shows the default script and the resulting behavior of the TextBox control in the worksheet.

Default Script

Sub TextBoxEvent_Start()
Rem TODO: Add your code here
End Sub

Sub TextBoxEvent_Exec(Inputs,Outputs)
Outputs(0).Value = TextBox.Text
End Sub

Sub TextBoxEvent_Stop()
Rem TODO: Add your code here
End Sub

How It Appears in the Worksheet

simple text box

Comments

In the script, notice three events, Start, Exec, and Stop. Since this text box control merely takes what is entered in the text box and returns it as output from the control, there is no code in either the Start or Stop events. In fact, all action associated with processing user entries in the text box itself should be written in the Exec event, including parsing text, converting the data type or any other processes. Procedures for formatting the textbox itself can be taken care of in the Start event or using the Properties dialog box. Here’s a slightly modified piece of script and a picture that shows its effect on the appearance and behavior of the control:

Modified Script

Sub TextBoxEvent_Start()
TextBox.ClientEdge = False
TextBox.Border = True
TextBox.BackColor = RGB(255,210,230)
TextBox.ForeColor = RGB(200,0,100)
End Sub

Sub TextBoxEvent_Exec(Inputs,Outputs)
Outputs(0).Value = "Hello, " + TextBox.Text + "!"
End Sub

Sub TextBoxEvent_Stop()
Rem TODO: Add your code here
End Sub

How It Appears in the Worksheet

modified text box

Comments

In this script, the appearance of the text box has been modified and the text entered by the user has been concatenated with text specified in the script.

Properties Dialog Box

If you would like to change the appearance of a text box without using the script, you can use the Properties Dialog box by right clicking the control and selecting Mathsoft TextBox Control Object Þ Properties from the popup menu. You see:

text box properties dialog box

Note that you can only change font settings for the text box control using the Properties dialog box. Font-related properties are not available through the script.

Sample File

Here is a sample file that demonstrates various uses of text boxes in a worksheet.

Launch QuickSheet Example


AutoHScroll Property

The AutoHScroll property gets or sets whether automatic horizontal scrolling is active.

Syntax

bMode = TextBox.AutoHScroll

TextBox.AutoHScroll = bMode

Element | Description
bMode | True indicates that automatic horizontal scrolling is active; false indicates that it is not active.

Remarks

Automatically scrolls the text in the control to the right when the user types a character at the end of the line. If AutoHScroll is false, only text that fits within the rectangular boundary is allowed.

Changes to the AutoHScroll property will not be reflected until you close and reopen the worksheet.


AutoVScroll Property

The AutoVScroll property gets or sets whether automatic vertical scrolling is active.

Syntax

bMode = TextBox.AutoVScroll

TextBox.AutoVScroll = bMode

Element | Description
bMode | True indicates that automatic vertical scrolling is active; false indicates that it is not active.

Remarks

Automatically scrolls the text in the control down when the user types a character at the end of the line. If AutoVScroll is false, only text that fits within the rectangular boundary is allowed.


BackColor Property

The BackColor property sets or gets the background color for the control.

Syntax

OLE_COLOR = TextBox.BackColor

TextBox.BackColor = OLE_COLOR

Element | Description
OLE_COLOR | A value that determines the background color of the control.

Remarks

Accepts any value in the valid hexadecimal range for an RGB color. For example, FFFFFF is the hexadecimal representation of white; 000000 is the hexadecimal representation of black.


Border Property (TextBox)

Border Property

The Border property sets or gets whether the TextBox has a border.

Syntax

bMode = TextBox.Border

TextBox.Border = bMode

Element | Description
bMode | True indicates that a border is visible; False indicates that it is not.

Remarks

Changes the appearance of the TextBox.


BorderStyle Property

The BorderStyle property changes the appearance of the TextBox.

Syntax

intStyle = TextBox.BorderStyle

TextBox.BorderStyle = intStyle

Element | Description
intStyle | Integer value that indicates the border style of the TextBox. 0 = no border; 1 = border.

Remarks

Changes the appearance of the TextBox.


ClientEdge Property (TextBox)

ClientEdge Property

The ClientEdge property sets or gets whether the TextBox has a client edge.

Syntax

bMode = TextBox.ClientEdge

TextBox.ClientEdge = bMode

Element | Description
bMode | True indicates that the TextBox has a client edge; False indicates that it does not.

Remarks

Changes the appearance of the TextBox.


Enabled Property (TextBox)

Enabled Property

The Enabled property sets or gets a value that determines whether an object can respond to user-generated events.

Syntax

bMode = TextBox.Enabled

TextBox.Enabled = bMode

Element | Description
bMode | True indicates that the TextBox is enabled; False indicates that it is disabled.

Remarks

A disable TextBox can not receive any user events, so it is similar to a static label.


Font Property (TextBox)

Font Property

Font property is used by the Properties page to set the font for the TextBox. This property is not used programmatically.


ForeColor Property

The ForeColor property sets or gets the foreground color for the control.

Syntax

OLE_COLOR = TextBox.ForeColor

TextBox.ForeColor = OLE_COLOR

Element | Description
OLE_COLOR | A value that determines the foreground color of the control.

Remarks

Accepts any value in the valid range for an RGB color. See also the BackColor property.


HorizontalScroll property (TextBox)

HorizontalScroll Property

The HorizontalScroll property gets or sets whether a horizontal scrollbar is visible in the TextBox.

Syntax

bMode = TextBox.HorizontalScroll

TextBox.HorizontalScroll = bMode

Element | Description
bMode | True indicates that the control will create a horizontal scrollbar on the bottom; False indicates that no scrollbar will be visible.

Remarks

This property is useful if the text extends beyond the width of the TextBox.


hWnd Property

The hWnd property gets the window handle of the window containing the control.

Syntax

OLE_HANDLE = TextBox.hWnd

Element | Description
OLE_HANDLE | The handle of the window containing the control.


LeftScrollBar Property

The LeftScrollBar property gets or sets whether a vertical scrollbar is shown on the left.

Syntax

bMode = TextBox.LeftScrollBar

TextBox.LeftScrollBar = bMode

Element | Description
bMode | True indicates that the control will show the vertical scrollbar on the left; False indicates that it will appear on the right.

Remarks

Changes the appearance of the TextBox.


Lowercase Property

The Lowercase property sets or gets a value that determines the default case of the text typed in the TextBox.

Syntax

bMode = TextBox.Lowercase

TextBox.Lowercase = bMode

Element | Description
bMode | True indicates that the added text will be converted to lowercase; False indicates that this is not enforced.

Remarks

See also the Uppercase property.


ModalFrame Property (TextBox)

ModalFrame Property

The ModalFrame property sets or gets a value that determines whether a modal frame is used. This property is not used programmatically.


Multiline Property (TextBox)

Multiline Property

The Multiline property sets or gets a value that determines whether a TextBox can have multiple lines of text.

Syntax

bMode = TextBox.Multiline

TextBox.Multiline = bMode

Element | Description
bMode | True indicates that the TextBox can have multiple lines; False indicates that it can not.

Remarks

Useful if the TextBox is likely to contain more than one line of text.


NoHideSelection Property

The NoHideSelection property sets or gets a value that determines the appearance of selected text within the TextBox.

Syntax

bMode = TextBox.NoHideSelection

TextBox.NoHideSelection = bMode

Element | Description
bMode | True indicates that the TextBox doesn't hide the selection; False indicates that it does.

Remarks

Normally, an edit control hides the selection when the control loses the input focus and inverts the selection when the control receives the input focus.


Number Property

The Number property sets or gets a value that determines whether only numbers are allowed in the TextBox.

Syntax

bMode = TextBox.Number

TextBox.Number = bMode

Element | Description
bMode | True indicates that the TextBox accepts only numbers; False indicates that it will accept other characters.

Remarks

Use this setting to filter user input to block out unwanted keystrokes.


OEMConvert Property

The OEMConvert property is used to handle non-ANSI characters entered in the text box control. Specifically, when this property is set, text entered in the edit control is converted from the ANSI character set to the OEM character set and then back to ANSI.

Syntax

bMode = TextBox.OEMConvert

TextBox.OEMConvert = bMode

Element | Description
bMode | True indicates that the TextBox performs the conversion; False indicates that it does not.

Remarks

The OEMConvert property ensures proper character conversion when the application calls the AnsiToOem Windows function to convert an ANSI string in the edit control to OEM characters, such as accented vowels, for example. This property is most useful when the text box passes a string containing a filename with non-ANSI characters to the operating system.


Password Property

The Password property sets or gets a value that determines whether input text is hidden with asterisks.

Syntax

bMode = TextBox.Password

TextBox.Password = bMode

Element | Description
bMode | True indicates that the TextBox text is visible to users as typed; False indicates that it is masked by asterisks.

Remarks

Use this setting to hide sensitive information but note that this property does not secure the text. It merely hides the keystroke input from users.


ReadOnly Property

The ReadOnly property sets or gets a value that determines whether the text is read-only or is editable.

Syntax

bMode = TextBox.ReadOnly

TextBox.ReadOnly = bMode

Element | Description
bMode | True indicates that the text is read-only; False indicates that the text is editable.

Remarks

Use this property to prevent users from editing the text.


RightToLeftReadingOrder Property (TextBox)

RightToLeftReadingOrder Property

The RightToLeftReadingOrder property sets or gets a value that determines whether the text is read right-to-left. Often used for Kanji.

Syntax

bMode = TextBox.RightToLeftReadingOrder

TextBox.RightToLeftReadingOrder = bMode

Element | Description
bMode | True indicates that the text ordering is right-to-left; False indicates left-to-right.

Remarks

Language localization may require this for languages that use a different ordering than English.


StaticEdge Property (TextBox)

StaticEdge Property

The StaticEdge property sets or gets a value that affects the appearance of the TextBox. This property is not used programmatically.


Text Property (TextBox)

Text Property

The Text property sets or gets the text of the TextBox.

Syntax

stringText = TextBox.Text

TextBox.Text = stringText

Element | Description
stringText | A string that indicates the text of the TextBox.

Remarks

This is probably the most commonly used property of this control. Used to retrieve the contents of the TextBox.


TextAlignment Property

Set at design time to Left, Center, or Right from the Properties dialog. Only enabled when Multiline property is checked. This property is not used programmatically.


Transparent Property (TextBox)

Transparent Property

The Transparent property sets or gets a value that determines whether the control "underneath" is visible. This property is not used programmatically.


Uppercase Property

The Uppercase property sets or gets a value that determines the case of the text permitted in the TextBox.

Syntax

bMode = TextBox.Uppercase

TextBox.Uppercase = bMode

Element | Description
bMode | True indicates that the added text will be converted to uppercase; False indicates that this is not enforced.

Remarks

See also the Lowercase property.


VerticalScroll Property (TextBox)

VerticalScroll Property

The VerticalScroll property gets or sets whether a verticall scrollbar is visible in the TextBox.

Syntax

bMode = TextBox.VerticalScroll

TextBox.VerticalScroll = bMode

Element | Description
bMode | True indicates that the control will create a vertical scrollbar on the right side; False indicates that no scrollbar will be visible.

Remarks

Useful for multiline TextBox.


WantsReturn Property

The WantsReturn property specifies that a carriage return be inserted when the user presses the ENTER key while entering text into a multiple-line edit control in a dialog box.

Syntax

bMode = TextBox.WantsReturn

TextBox.WantsReturn = bMode

Element | Description
bMode | True indicates insert a carriage return in the block of text entered by the user; false has no effect on the control and is the default setting.

Remarks

This property is only available if the Multiline property has been set to true.


Overview of List Boxes

Mathsoft ListBox Control

Overview

The Mathsoft ListBox Control allows you to accept user input in the form of a selection from a list. The default output is the number of the item selected in the list, but it can be converted to a string or other data type in the script. You can change the appearance of a list box using the Properties dialog box or access its properties through the script. Descriptions and code examples for all properties are given in the Help pages that follow.

Simple Annotated Example

Here's an example that shows the default script and the resulting behavior of the ListBox control in the worksheet.

Default Script

Rem Initialize List Box
ListBox.ResetContent()

Rem Add Strings here as needed
ListBox.AddString("One")
ListBox.AddString("Two")
ListBox.AddString("Three")

Rem Initialize Selection If desired
ListBox.CurSel = 0

Sub ListBoxEvent_Start()
Rem TODO: Add your code here
End Sub

Sub ListBoxEvent_Exec(Inputs,Outputs)
Outputs(0).Value = ListBox.CurSel + 1
End Sub

Sub ListBoxEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub ListBox_SelChanged()
ListBox.Recalculate()
End Sub

Sub ListBox_DblClick()
ListBox.Recalculate()
End Sub

How It Appears in the Worksheet

simple list box

Comments

In the script, notice that there are five events, Start, Exec, Stop, SelChanged, and DblClick. However, the list box is initialized and populated outside these events so that the control calculates and sends output to the worksheet whether the user has actively selected a list box item or not. If you wish to effect changes in the contents of the list based on other events in the worksheet, you have to move this code inside the Start event.

In general, the Start event may be used to further modify or manipulate the appearance of the list box or the elements within it. Alternatively, procedures for formatting the list box can be done using the Properties dialog box, including font formatting, which may only be done through the Properties dialog. The Exec event is where inputs and outputs can be processed, including converting the selection from the default integer output to other numerical or string output. The SelChanged and DblClick events are generally used to re-execute the control after the user has changed their selection, though these events might fire other actions, such as alerts or script-based calculations. Here's a slightly modified piece of script and a picture showing its effect on the appearance and behavior of the control:

Modified Script

Rem Initialize List Box
ListBox.ResetContent()

Rem Add Strings here as needed
ListBox.AddString("tetrahedron")
ListBox.AddString("cube")
ListBox.AddString("octahedron")
ListBox.AddString("icosahedron")
ListBox.AddString("dodecahedron")

Rem Initialize Selection If desired
ListBox.CurSel = 0

Sub ListBoxEvent_Start()
Rem TODO: Add your code here
End Sub

Sub ListBoxEvent_Exec(Inputs,Outputs)
Outputs(0).Value = ListBox.GetText(CurSel)
End Sub

Sub ListBoxEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub ListBox_SelChanged()
ListBox.Recalculate()
End Sub

Sub ListBox_DblClick()
ListBox.Recalculate()
End Sub

How It Appears in the Worksheet

modified list box

Comments

In this script, the items in the list box have been modified and the output has been converted to a string using the GetText method supported by the ListBox control.

Properties Dialog Box

If you would like to change the appearance of a list box without using the script, you can use the Properties Dialog box by right clicking on the control and selecting Mathsoft ListBox Control Object Þ Properties from the popup menu. You see:

Note that you can only change font settings for the list box control using the Properties dialog box. Font-related properties are not available through the script.

Sample File

Here is a sample file that demonstrates use of list boxes in a worksheet.

Launch QuickSheet Example


AcceptFiles Property (ListBox)

AcceptFiles Property

The AcceptFiles property sets or gets whether the ListBox accepts files via drag and drop. Currently, this property is disabled.


Border Property (ListBox)

Border Property

The Border property sets or gets whether the ListBox has a border.

Syntax

bMode = ListBox.Border

ListBox.Border = bMode

Element | Description
bMode | True indicates that a border is visible; False indicates that it is not.

Remarks

Changes the appearance of the ListBox.


ClientEdge Property (ListBox)

ClientEdge Property

The ClientEdge property sets or gets whether the ListBox has a client edge.

Syntax

bMode = ListBox.ClientEdge

ListBox.ClientEdge = bMode

Element | Description
bMode | True indicates that the ListBox has a client edge; False indicates that it does not.

Remarks

Changes the appearance of the ListBox.


Count Property (ListBox)

Count Property

The Count property is read-only and returns the number of items in the ListBox.

Syntax

longCount = ListBox.Count

Element | Description
longCount | The number of items in the ListBox.

Remarks

This important property can be used to set up a loop to iterate through the control using methods such as GetText.


CurSel Property

The CurSel property sets or gets the index of the currently selected item in the ListBox.

Syntax

longSelIndex = ListBox.CurSel

ListBox.CurSel = longSelIndex

Element | Description
longSelIndex | The index of the selected item or item to select. Zero based.

Remarks

Note that index is zero based, so first item in list has index of 0. Returns constant LBERR if no item selected.


DisableNoScroll Property

The DisableNoScroll property sets or gets whether the ListBox shows a disabled scroll bar when it does not contain enough items to fill visible space.

Syntax

bMode = ListBox.DisableNoScroll

ListBox.DisableNoScroll = bMode

Element | Description
bMode | True indicates that a disabled scrollbar is shown when not enough items are present; False indicates that no scrollbar is shown.


HorizontalScroll Property (ListBox)

HorizontalScroll Property

The HorizontalScroll property gets or sets whether a horizontal scrollbar is visible in the ListBox.

Syntax

bMode = ListBox.HorizontalScroll

ListBox.HorizontalScroll = bMode

Element | Description
bMode | True indicates that the control will create a horizontal scrollbar on the bottom; False indicates that no scrollbar will be visible.


LBERR Property

The LBERR property sets or gets the LBERR constant.

Syntax

longLBERR = ListBox.LBERR

ListBox.LBERR = longLBERR

Element | Description
longLBERR | A value that indicates the setting of the LBERR constant.

Remarks

Use this property to test for errors on all listbox properties and methods, except AddString and InsertString, in which case use the LBERRSPACE property to test for insufficient memory. For example, the LBERR constant is returned as error by CurSel property when no item is selected.


LBERRSPACE Property

The LBERRSPACE property sets or gets the LBERRSPACE constant.

Syntax

longLBERRSPACE = ListBox.LBERRSPACE

ListBox.LBERRSPACE = longLBERRSPACE

Element | Description
longLBERRSPACE | A value that indicates the setting of the LBERRSPACE constant.

Remarks

Use the LBERRSPACE property to test if there is enough memory to complete an AddString or InsertString method call. In all other cases, use the LBERR property to test for errors.


ModalFrame Property (ListBox)

ModalFrame Property

The ModalFrame property sets or gets a value that determines whether a modal frame is used.

Syntax

bMode = ListBox.ModalFrame

ListBox.ModalFrame = bMode

Element | Description
bMode | True indicates that the ListBox has a modal frame; False indicates that it does not.

Remarks

This setting affects the appearance of the ListBox only.


NoIntegralHeight Property

The NoIntegralHeight property gets or sets whether or not the ListBox partially displays list entries extending above or below the edge of the ListBox.

Syntax

bMode = ListBox.NoIntegralHeight

ListBox.NoIntegralHeight = bMode

Element | Description
bMode | True indicates that the control will only display full list entries; False indicates that the control will display part of an entry which extends above or below the edge of the ListBox.


RightAlignedText Property (ListBox)

RightAlignedText Property

The RightAlignedText property sets or gets a value that determines whether the text is right justified.

Syntax

bMode = ListBox.RightAlignedText

ListBox.RightAlignedText = bMode

Element | Description
bMode | True indicates that the text is right-justified; False that it is not.

Remarks

Right justification is often useful for numerical inputs.


RightToLeftReadingOrder Property (ListBox)

RightToLeftReadingOrder Property

The RightToLeftReadingOrder property sets or gets a value that determines whether the text is read right-to-left.

Syntax

bMode = ListBox.RightToLeftReadingOrder

ListBox.RightToLeftReadingOrder = bMode

Element | Description
bMode | True indicates that the text ordering is right-to-left; False indicates left-to-right.

Remarks

Language localization may require this for languages that use a different ordering than English.


Sort Property

The Sort property sets or gets whether the ListBox items are displayed in alphabetical order.

Syntax

bMode = ListBox.Sort

ListBox.Sort = bMode

Element | Description
bMode | True indicates that contents of ListBox will be sorted; False indicates that contents appear in original order.

Remarks

Affects display only. Internally, items remain in original order.


StaticEdge Property (ListBox)

StaticEdge Property

The StaticEdge property sets or gets a value that determines the appearance of the ListBox.

Syntax

bMode = ListBox.StaticEdge

ListBox.StaticEdge = bMode

Element | Description
bMode | True indicates that a static edge is used; False indicates that it is not.

Remarks

Changes the appearance of the ListBox only.


Transparent Property (ListBox)

Transparent Property

The Transparent property sets or gets a value that determines whether the control "underneath" is visible.

Syntax

bMode = ListBox.Transparent

ListBox.Transparent = bMode

Element | Description
bMode | True indicates that the ListBox is transparent; False indicates that it is solid.

Remarks

A ListBox is often rendered as solid.


VerticalScroll property (ListBox)

VerticalScroll Property

The VerticalScroll property gets or sets whether a vertical scrollbar is visible in the ListBox.

Syntax

bMode = ListBox.VerticalScroll

ListBox.VerticalScroll = bMode

Element | Description
bMode | True indicates that the control will create a vertical scrollbar on the right side; False indicates that no scrollbar will be visible.


AddString Method

The AddString method adds a string item to the ListBox.

Syntax

longRet = ListBox.AddString(strItem as String)

Element | Description
longRet | Returns the index at which string was added.
strItem | A string to be added to the ListBox.

Remarks

Adds a string to the end of the list. If Sort is TRUE, string is inserted into the list in its sorted position.


DeleteString Method

The DeleteString method deletes a string item from the ListBox

Syntax

longRet = ListBox.DeleteString(intItem as Integer)

Element | Description
longRet | Returns the index from which the string was deleted.
intItem | A integer indicating the index of the item to remove.


FindString Method

The FindString method finds the index of a particular item in a ListBox.

Syntax

longRet = ListBox.FindString(longStartAfter as Long, strItem as String)

Element | Description
longRet | Returns the index at which the string was found or LBERR if not found.
strItem | The string to search for.
longStartAfter | An integer indicating the index at which to begin search. If set to -1, entire ListBox is searched.

Remarks

Search is case independent.


FindStringExact Method

The FindStringExact method finds the index of a particular item in a ListBox.

Syntax

longRet = ListBox.FindStringExact(longStartAfter as Long, strItem as String)

Element | Description
longRet | Returns the index at which the string was found or LBERR if not found.
strItem | The string to search for.
longStartAfter | An integer indicating the index at which to begin search. If set to -1, entire ListBox is searched.

Remarks

Search is case independent.


GetText Method

The GetText method get the text of an item at a specified index.

Syntax

strRet = ListBox.GetText(longIndex as Long)

Element | Description
strRet | The string at the specified index.
longIndex | The index at which to find the text.

Remarks

Note that index is zero based.


InsertString Method

The InsertString method inserts a string into the ListBox at a specified index.

Syntax

longRet = ListBox.InsertString(longIndex as Long, strItem as String)

Element | Description
longRet | Returns the index at which the string was inserted.
longIndex | The location at which to insert the string.
strItem | A string to be inserted into the ListBox.


Recalculate Method (ListBox)

Recalculate Method

The Recalculate method recalculates the control.

Syntax

ListBox.Recalculate()

Remarks

Use within the framework of the Mathcad worksheet to force the scripted object to recalculate. This fires the Start, Exec, and Stop events. This method can be called from within events the control might listen for, including the SelChanged event. After the ListBox recalculates, any dependent expressions in the Mathcad worksheet will also update if AutoCalculate is on.


ResetContent Method

The ResetContent method removes all strings from the ListBox.

Syntax

ListBox.ResetContent()

Remarks

Use to clear the contents of the ListBox.


SelectString Method

The SelectString method selects the string at a specified index of the ListBox.

Syntax

longRet = ListBox.SelectString(longStartAfter as Long, strItem as String)

Element | Description
longRet | Returns the index of the selected string, else returns LBERR if the string is not found.
longStartAfter | The location at which to start searching. -1 indicates to search the entire ListBox.
strItem | A string to select.


DblClick Event (ListBox)

DblClick Event

The DblClick event is fired when the ListBox is double clicked.

Syntax

Private Sub ListBox_DblClick()

Remarks

Can be used to confirm user selection. Within Mathcad framework, the Recalculate method can be called to update control and retrieve the current selection, for example.


Error Event (ListBox)

Error Event

The Error event is fired when an error occurs.

Syntax

Private Sub ListBox_Error(short Number, BSTR* Description, SCODE Scode, BSTR Source, BSTR HelpFile, long HelpContext, boolean* CancelDisplay);


SelChanged Event

The SelChanged event is fired when the selection in the ListBox changes.

Syntax

Private Sub ListBox_SelChanged()

Remarks

Can be used to confirm user selection. Within the Mathcad framework, the Recalculate method can be called to update control and retrieve the current selection in the Exec event handler, using the CurSel property and the GetText method.


Overview of Buttons

Mathsoft Button Control

Overview

The Mathsoft Button Control allows you to accept user input in the form of button selection and de-selection. By default, the button returns either a 1 or a 0. Buttons come in three varieties: push buttons, radio buttons, and check boxes. They all operate the same way by allowing the user to set an "on" state and an "off" state. You can change the appearance of a button using the Properties dialog box or access its properties through the script. Descriptions and code examples for all properties are given in the Help pages that follow.

Simple Annotated Example

Here's an example that shows the default script and the resulting behavior of the Push Button control in the worksheet. You can also look at simple and modified examples of the Radio Button control and the Check Box control.

Default Script

Dim state

Sub PushBtnEvent_Start()
Rem TODO: Add your code here
End Sub

Sub PushBtnEvent_Exec(Inputs,Outputs)
Outputs(0).value = state
End Sub

Sub PushBtnEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub PushBtn_Click()
If state = 0 Then
state = 1
Else
state = 0
End If
PushBtn.Recalculate()
End Sub

How It Appears in the Worksheet

simple push button

Comments

In the script, notice that there are four events, Start, Exec, Stop, and Click. The Exec event is where inputs and outputs can be processed, namely returning the state of the button. Procedures for formatting the button itself can be taken care of in the Start event or using the Properties dialog box. The Click event is most important where push buttons are concerned because that's where state changes are handled and where the control is re-executed after the user has changed their selection. Notice that in a default push button, there is no visible manifestation of a state change. Here's a slightly modified piece of script and a picture showing its effect on the appearance and behavior of the control:

Modified Script

Dim state

Sub PushBtnEvent_Start()
Rem TODO: Add your code here
End Sub

Sub PushBtnEvent_Exec(Inputs,Outputs)
Outputs(0).value = state
End Sub

Sub PushBtnEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub PushBtn_Click()
If state = 0 Then
state = 1
PushBtn.Text = "On"
PushBtn.Flat = True
Else
state = 0
PushBtn.Text = "Off"
PushBtn.Flat = False
End If
PushBtn.Recalculate()
End Sub

How It Appears in the Worksheet

modified push button

Comments

In this script, visible elements have been added to the Click event to show the end user the state change. Namely, when the user clicks the button once, the button reads "On" and is displayed as flat. Then, when the user clicks the button again, the button reads "Off" and is displayed as raised.

Properties Dialog Box

If you would like to change the appearance of a button without using the script, you can use the Properties Dialog box by right-clicking on the control and selecting Mathsoft Button Control Object Þ Properties from the popup menu. You see:

Note that you can only change a single state setting for the push button control using the Properties dialog. In order to program appearance effects for both states of the button, you must use the script. Any settings you have programmed into the script override settings made in the Properties dialog.

Sample File

Here is a sample file that demonstrates various uses of buttons in a worksheet.

Launch QuickSheet Example


Auto Property

The Auto property sets or gets a value that determines whether the Button handles its state.

Syntax

bMode = Button.Auto

Button.Auto = bMode

Element | Description
bMode | True indicates that the Button handles its state; False indicates that the state must be handled manually.


AutoSize Property (Button)

AutoSize Property

The AutoSize property sets or gets whether autosize is active.

Syntax

bMode = Button.AutoSize

Button.AutoSize = bMode

Element | Description
bMode | True indicates that autosize is active; false indicates that autosize is not active.

Remarks

Use to resize control automatically based on caption length.


Bitmap Property

The Bitmap property is used by the Properties pages to set the bitmap image for the Button. Not used programmatically.


ButtonID Property

The ButtonID property sets or gets a number that is used as reference when control is part of a radio Button group.

Syntax

intID = Button.ButtonID

Button.ButtonID = intID

Element | Description
intID | Number that is used to reference control in radio-Button group.


ButtonStyle Property

The ButtonStyle property sets or gets a number that determines the style of the Button.

Syntax

intStyle = Button.ButtonStyle

Button.ButtonStyle = intStyle

Element | Description
intStyle | Number that defines the style of the Button; either default checkbox (1), push button (0), or radio button (2).

Remarks

Note that this property can be set from Properties pages via a drop down list. For further control over the Button's appearance, see the Type grouping on the General tab of the Properties page.


Check Property

The Check property sets or gets a value that determines the checked state of the Button.

Syntax

bMode = Button.Check

Button.Check = bMode

Element | Description
bMode | True indicates that the radio button is selected or checkbox is checked; False indicates that it is unchecked.

Remarks

The Check property of the Button is commonly queried after the Click event. This property is only useful for check boxes and radio buttons. It is not applicable to push buttons.


Enabled Property (Button)

Enabled Property

The Enabled property sets or gets a value that determines whether an object can respond to user-generated events.

Syntax

bMode = Button.Enabled

Button.Enabled = bMode

Element | Description
bMode | True indicates that Button can be checked and unchecked; False indicates that it can not.

Remarks

If Button is disabled, it can not receive user events.


Flat Property

The Flat property sets or gets a value that determines the appearance of the Button, whether flat or 3D.

Syntax

bMode = Button.Flat

Button.Flat = bMode

Element | Description
bMode | True indicates that Button has a flat appearance; False indicates that Button has the more common 3D appearance.


Font Property (Button)

Font Property

The Font property is used by the Properties page to set the font for the caption. Not used programmatically.


GroupID Property

The GroupID property sets or gets a number that is used to a group of radio buttons.

Syntax

intID = Button.GroupID

Button.GroupID = intID

Element | Description
intID | Number that is used to refer to a group of radio buttons.

Remarks

This property is only useful for radio buttons. It does not apply to check boxes or push buttons.


HorizontalAlignment Property

Not currently used.


Icon Property

The Icon property is used by the Properties page to set the icon image for the button. Not used programmatically.


LeftText Property

The LeftText property sets or gets a value that determines whether the Button's caption is left aligned.

Syntax

bMode = Button.LeftText

Button.LeftText = bMode

Element | Description
bMode | True indicates that Button's caption is left-aligned; False indicates that it is not.


Multiline Property (Button)

Multiline Property

The Multiline property sets or gets a value that determines whether the Button's caption can wrap to multiple lines.

Syntax

bMode = Button.Multiline

Button.Multiline = bMode

Element | Description
bMode | True indicates that Button's caption can occupy multiple lines; False indicates that it can only occupy a single line.

Remarks

This properly is commonly used when the text might occupy more than one line.


PushLike Property

The PushLike property sets or gets a value that determines the appearance of the check box (button).

Syntax

bMode = Button.PushLike

Button.PushLike = bMode

Element | Description
bMode | True indicates that the checkbox should appear to user as a push button; False indicates that it does not.

Remarks

This property may be used to program a button that behaves like a check box but looks like a push button. This property is only useful for check boxes.


Text Property (Button)

Text Property

The Text property sets or gets the caption of the Button.

Syntax

stringText = Button.Text

Button.Text = stringText

Element | Description
stringText | A string that indicates the Button's caption.

Remarks

Can be set via Properties page or dynamically at run-time.


UseBitmap Property

The UseBitmap property sets or gets a value that determines whether the Button uses a bitmap for its face.

Syntax

bMode = Button.UseBitmap

Button.UseBitmap = bMode

Element | Description
bMode | True indicates that the Button uses a bitmap image; False that it uses only the text caption.


UseIcon Property

The UseIcon property sets or gets a value that determines whether the Button uses a icon for its face.

Syntax

bMode = Button.UseIcon

Button.UseIcon = bMode

Element | Description
bMode | True indicates that the Button uses an icon for its face; False indicates that it uses only the caption.


VerticalAlignment Property

Not currently used.


AboutBox Method

The AboutBox method displays the about box dialog.

Syntax

Button.AboutBox()


Recalculate Method (Button)

Recalculate Method

The Recalculate method recalculates the control.

Syntax

Button.Recalculate()

Remarks

Use within the framework of the Mathcad worksheet to force the scripted object to recalculate. This fires the Start, Exec, and Stop events. This method can be called from within events the control might listen for, such as the Click event. After the Button recalculates, any dependent expressions in the Mathcad worksheet will also update if AutoCalculate is on.


SelectedButton Method

The SelectedButton method returns the Button ID of the selected button in a button group.

Syntax

intRet = Button.SelectedButton()

Element | Description
intRet | Returns the button ID of the button in the button group.

Remarks

This method is only useful for radio buttons.


Click Event

The Click event is fired when the button is single clicked.

Syntax

Private Sub Button_Click()

Remarks

This event is commonly used for the button, checkbox, or push button styles to process code. In the Click event handler, you would likely call the Recalculate method. Then in the Exec event handler, you would query the Check property to determine the state of the Button.


DblClick Event (Button)

DblClick Event

The DblClick event is fired when the button is double clicked.

Syntax

Private Sub Button_DblClick()

Remarks

Not commonly used for buttons.


Error Event (Button)

Error Event

The Error event is fired when an error occurs.

Syntax

Private Sub Button_Error(short Number, BSTR* Description, SCODE Scode, BSTR Source, BSTR HelpFile, long HelpContext, boolean* CancelDisplay);


KeyDown Event

The KeyDown event is fired when a key is pressed.

Syntax

Private Sub Button_KeyDown(KeyCode As Integer, Shift As Integer)

Element | Description
KeyCode | An integer that represents the key code of the key that was pressed or released.
Shift | The state of SHIFT, CTRL, and ALT.

Remarks

KeyDown, KeyPress, and KeyUp are fired in sequence.


KeyPress Event

The KeyPress event is fired when a key is pressed.

Syntax

Private Sub Button_KeyPress(KeyAscii As Integer)

Element | Description
KeyAscii | An integer value that represents a standard numeric ANSI key code.

Remarks

Commonly used to intercept keystrokes received by a form or control.


KeyUp Event

The KeyUp event is fired when a key is released.

Syntax

Private Sub Button_KeyUp(KeyCode As Integer, Shift As Integer)

Element | Description
KeyCode | An integer that represents the key code of the key that was pressed or released.
Shift | The state of SHIFT, CTRL, and ALT.

Remarks

KeyPress event is more commonly handled.


MouseDown Event

The MouseDown event is fired when the user presses a mouse button.

Syntax

Private Sub Button_MouseDown(Button As Integer, Shift As Integer, x As OLE_XPOS_PIXELS, y As OLE_YPOS_PIXELS)

Element | Description
Button | An integer value that identifies which mouse button caused the event.
Shift | The state of SHIFT, CTRL, and ALT.
x,y | The horizontal or vertical position, in points, from the left or top edge of the form, Frame, or Page.


MouseMove Event

The MouseMove event is fired when the user moves the mouse over the control.

Syntax

Private Sub Button_MouseMove(Button As Integer, Shift As Integer, x As OLE_XPOS_PIXELS, y As OLE_YPOS_PIXELS)

Element | Description
Button | An integer value that identifies which mouse button caused the event.
Shift | The state of SHIFT, CTRL, and ALT.
x,y | The horizontal or vertical position, in points, from the left or top edge of the form, Frame, or Page.


MouseUp Event

The MouseUp event is fired when the user releases the mouse button.

Syntax

Private Sub Button_MouseUp(Button As Integer, Shift As Integer, x As OLE_XPOS_PIXELS, y As OLE_YPOS_PIXELS)

Element | Description
Button | An integer value that identifies which mouse button caused the event.
Shift | The state of SHIFT, CTRL, and ALT.
x,y | The horizontal or vertical position, in points, from the left or top edge of the form, Frame, or Page.


ReadyStateChange Event

The ReadyStateChange event is fired when a control transitions to the next ready state due to the amount of data received.

Syntax

Private Sub Button_ReadyStateChange()


SelectionChange Event

The SelectionChange event is fired when the selection of the Radio-Button group changes.

Syntax

Private Sub Button_SelectionChange()


Radio Button Control Examples

Mathsoft Radio Button Control Examples

Simple Annotated Example

Here's an example that shows the default script and the resulting behavior of the Radio Button control in the worksheet.

Default Script

Sub RadioBtnEvent_Start()
Rem TODO: Add your code here
End Sub

Sub RadioBtnEvent_Exec(Inputs,Outputs)
Outputs(0).Value = RadioBtn.SelectedButton()
End Sub

Sub RadioBtnEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub RadioBtn_Click()
RadioBtn.Recalculate()
End Sub

Sub RadioBtn_SelectionChange()
RadioBtn.Recalculate()
End Sub

How It Appears in the Worksheet

simple radio button

Comments

In the script, notice that there are five events, Start, Exec, Stop, Click, and Selection Change. The Exec event is where inputs and outputs can be processed, namely returning the state of the button. In the case of radio buttons, this is where state changes are handled because both check boxes and radio buttons support the Check property which delivers the state of the button. Procedures for formatting the button itself can be taken care of in the Start event or using the Properties dialog box. The Click event is where the control is re-executed after the user has clicked the control. The Selection Change event is needed to support groups of radio buttons in which case a change of state to the individual radio button must take place when another button in the group is clicked. Here are the scripts for a group of radio buttons working together, and their effect on the appearance and behavior of the controls:

Modified Scripts

First Radio Button

Sub RadioBtnEvent_Start()
RadioBtn.GroupID = 1
RadioBtn.ButtonID = 1
RadioBtn.Text = "Radio Button 1"
End Sub

Sub RadioBtnEvent_Exec(Inputs,Outputs)
Outputs(0).Value = RadioBtn.SelectedButton()
End Sub

Sub RadioBtnEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub RadioBtn_Click()
RadioBtn.Recalculate()
End Sub

Sub RadioBtn_SelectionChange()
RadioBtn.Recalculate()
End Sub

All Other Radio Buttons

Sub RadioBtnEvent_Start()
RadioBtn.GroupID = 1
RadioBtn.ButtonID = 2
RadioBtn.Text = "Radio Button 2"
End Sub

Sub RadioBtnEvent_Exec(Inputs,Outputs)
Rem TODO: Add your code here
End Sub

Sub RadioBtnEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub RadioBtn_Click()
RadioBtn.Recalculate()
End Sub

Sub RadioBtn_SelectionChange()
RadioBtn.Recalculate()
End Sub

How It Appears in the Worksheet

modified radio button

Comments

In the script for the first button, the group identifier and the button identifier are specified, and the label has been changed. All other aspects of the script remain the same. Output is specified as the number of the radio button selected. In the script for the remaining buttons, the group and button identifiers are updated and the label changed, but there is no output specified. Because the script for these buttons does not require an output variable, you can remove it by right clicking on the control and selecting Remove Output Variable from the popup menu.

Sample File

Here is a sample file that demonstrates the use of radio buttons in a worksheet.

Launch QuickSheet Example


Check Box Control Examples

Mathsoft Check Box Control Examples

Simple Annotated Example

Here's an example that shows the default script and the resulting behavior of the Check Box control in the worksheet.

Default Script

Sub CheckBoxEvent_Start()
Rem TODO: Add your code here
End Sub

Sub CheckBoxEvent_Exec(Inputs,Outputs)
If CheckBox.check Then
Outputs(0).Value = 1
Else
Outputs(0).Value = 0
End If
End Sub

Sub CheckBoxEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub CheckBox_Click()
CheckBox.Recalculate()
End Sub

How It Appears in the Worksheet

simple check box

Comments

In the script, notice that there are four events, Start, Exec, Stop, and Click. The Exec event is where inputs and outputs can be processed, namely returning the state of the button. In the case of check boxes, this is where state changes are handled because both check boxes and radio buttons support the Check property which delivers the state of the button. Procedures for formatting the button itself can be taken care of in the Start event or using the Properties dialog box. The Click event is where the control is re-executed after the user has changed their selection. Here's a slightly modified piece of script and its effect on the appearance and behavior of the control:

Modified Script

Sub CheckBoxEvent_Start()
CheckBox.Text = "Check here to enable default parameters in the worksheet."
End Sub

Sub CheckBoxEvent_Exec(Inputs,Outputs)
If CheckBox.check Then
Outputs(0).Value = 1
Outputs(1).Value = 2
Outputs(2).Value = 3
Else
Outputs(0).Value = "no value specified"
Outputs(1).Value = "no value specified"
Outputs(2).Value = "no value specified"
End If
End Sub

Sub CheckBoxEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub CheckBox_Click()
CheckBox.Recalculate()
End Sub

How It Appears in the Worksheet

modified check box

Comments

In this script, two more output variables were added and the script in the Exec event was modified to send data out to these variables. Also, the text of the check box was changed to prompt the user to check the box.

Sample File

Here is a sample file that demonstrates various uses of buttons in a worksheet.

Launch QuickSheet Example


Overview of Sliders

Mathsoft Slider Control

Overview

The Mathsoft Slider Control allows you to accept user input in the form of relative position on a slider. The default output is an integer between 1 and 100, depending on the position of the slider, but a slider can be set to any numerical range. You can change the appearance of a slider using the Properties dialog box or access its properties through the script. Descriptions and code examples for all properties are given in the Help pages that follow.

Simple Annotated Example

Here's an example that shows the default script and the resulting behavior of the Slider control in the worksheet.

Default Script

Sub SliderEvent_Start()
Rem TODO: Add your code here
End Sub

Sub SliderEvent_Exec(Inputs,Outputs)
Outputs(0).Value = Slider.Position
End Sub

Sub SliderEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub Slider_ValueChanged()
Slider.Recalculate()
End Sub

How It Appears in the Worksheet

Comments

In the script, notice that there are four events, Start, Exec, Stop, and ValueChanged. The Exec event is where inputs and outputs can be processed, including converting the selection from the default integer output to other numerical output. Procedures for formatting the slider itself can be taken care of in the Start event or using the Properties dialog box. The ValueChanged event is generally used to re-execute the control after the user has changed their selection, though this event might fire other actions, such as alerts or script-based calculations. Here's a slightly modified piece of script and its effect on the appearance and behavior of the control:

Modified Script

Sub SliderEvent_Start()
Slider.MinRange = –10
Slider.MaxRange = 10
Slider.TickFrequency = 1
Slider.Point = 2
End Sub

Sub SliderEvent_Exec(Inputs,Outputs)
Outputs(0).Value = Slider.Position/2
End Sub

Sub SliderEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub Slider_ValueChanged()
Slider.Recalculate()
End Sub

How It Appears in the Worksheet

Comments

In this script, the values that control the range and frequency of ticks on the slider have been set. These could also have been set in the Properties dialog. Also, in order to get decimal output, all values have been divided by 2. You can perform any algebraic conversion on the Slider.Position value in order to get the output you want, but this must be done in the script, not through the Properties dialog. Additionally, the pointer's appearance has been changed. You must resize the control in the worksheet itself using the region sizing handles.

Properties Dialog Box

If you would like to change the appearance of a slider without using the script, you can use the Properties Dialog box by right-clicking on the control and selecting Mathsoft Slider Control Object Þ Properties from the popup menu. You see:

Note that you must enter integer values for Min, Max, and Tick Frequency in the Properties dialog. To get non-integer values, you must use the script.

Sample File

Here is a sample file that demonstrates various uses of sliders in a worksheet.

Launch QuickSheet Example


AutoTicks Property

The AutoTicks property sets or gets whether the slider displays a tick mark for each increment in its range of values.

Syntax

bMode = Slider.AutoTicks

Slider.AutoTicks = bMode

Element | Description
bMode | True indicates that a tick appears at the interval specified by the TickFrequency property; False indicates that ticks will only appear at the ends of the control.

Remarks

Used to adjust the number of ticks on the Slider.


Border Property (Slider)

Border Property

The Border property sets or gets whether the Slider has a border.

Syntax

bMode = Slider.Border

Slider.Border = bMode

Element | Description
bMode | True indicates that a border is visible; False indicates that it is not.

Remarks

Affects the appearance of the Slider.


ClientEdge Property (Slider)

ClientEdge Property

The ClientEdge property sets or gets whether the Slider has a client edge.

Syntax

bMode = Slider.ClientEdge

Slider.ClientEdge = bMode

Element | Description
bMode | True indicates that the Slider has a client edge; False indicates that it does not.

Remarks

Affects the appearance of the Slider.


EnableSelection Property

The EnableSelection property sets or gets whether a selection range is displayed that highlights a portion of the Slider's range.

Syntax

bMode = Slider.EnableSelection

Slider.EnableSelection = bMode

Element | Description
bMode | True indicates that a portion of the range can be selected and highlighted; False indicates single value selection only.

Remarks

Affects the appearance of the Slider.


LineSize Property

The LineSize property gets or sets a value that indicates a small interval for moving the slider with the keyboard or mouse wheel.

Syntax

longLineSize = Slider.LineSize

Slider.LineSize = longLineSize

Element | Description
longLineSize | A value that indicates the small incremental adjustment to the Slider position while using the keyboard or mouse wheel.

Remarks

Affects the feel and operation of the Slider. Use a small value to allow fine adjustment of the slider via the arrow keys.


MinRange Property

The MinRange property gets or sets the minimum value of the control.

Syntax

longMin = Slider.MinRange

Slider.MinRange = longMin

Element | Description
longMin | A value that indicates the minimum value of the Slider control.

Remarks

This property can also be accessed via the Properties page.


MaxRange Property

The MaxRange property gets or sets the maximum value of the control.

Syntax

longMax = Slider.MaxRange

Slider.MaxRange = longMax

Element | Description
longMax | A value that indicates the maximum value of the Slider control.

Remarks

This property can also be accessed via the Properties page.


NumTicks Property

The NumTicks property is a read-only property that indicates how many ticks are displayed, including the first and last ticks that are always created.

Syntax

longNumTicks = Slider.NumTicks

Element | Description
longNumTicks | A value that indicates the number of ticks displayed on the Slider.

Remarks

This is a read-only property. See TickFrequency property to set the number of ticks on the Slider.


Orientation Property

The Orientation property gets or sets a value that indicates the orientation of the Slider control.

Syntax

longOrientation = Slider.Orientation

Slider.Orientation = longOrientation

Element | Description
longOrientation | Defines the orientation of the slider. 0 = horizontal Slider, 1 = vertical Slider.

Remarks

Affects the appearance of the Slider. This property can also be accessed via the Properties page.


PageSize Property

The PageSize property gets or sets a value that indicates a large interval for moving the slider with the keyboard or mouse wheel.

Syntax

longPageSize = Slider.PageSize

Slider.PageSize = longPageSize

Element | Description
longPageSize | A value that indicates the large incremental adjustment to the Slider position while using the keyboard or mouse wheel.

Remarks

Affects the operation of the Slider. Use a large value to quickly change the Slider position using the Page Up and Page Down keys, or by clicking to either side of the Slider pointer. Use Home and End to move quickly to the MinRange and MaxRange values via the keyboard, independent of the PageSize setting.


Point Property

The Point property gets or sets a value that indicates the style of the pointer.

Syntax

longStyle = Slider.Point

Slider.Point = longStyle

Element | Description
longStyle | Defines the pointer style. 0 = no point, 1 = top / left, 2 = right/bottom.

Remarks

Setting the property to 0 gives a rectangular pointer. Setting the property to 1 gives a pointer toward the top or left. Setting the property to 2 gives a pointer toward the right or bottom.


Position Property

The Position property gets or sets a value that indicates the logical position of the pointer.

Syntax

longPos = Slider.Position

Slider.Position = longPos

Element | Description
longPos | A value that determines the logical position of the pointer.

Remarks

This is probably the most important property of the Slider control. Use this property to get the current position by invoking the Recalculate method in the ValueChanged event, and querying this property in the Exec event.


SelectionLow Property

The SelectionLow property gets or sets a value that indicates the low value of the selection range

Syntax

longSelLow = Slider.SelectionLow

Slider.SelectionLow = longSelLow

Element | Description
longSelLow | A value that indicates the low value of the selection range.

Remarks

The value for the SelectionLow property must be within the MinRange and MaxRange properties and less than the SelectionHigh property.


SelectionHigh Property

The SelectionHigh property gets or sets a value that indicates the high value of the selection range

Syntax

longSelHigh = Slider.SelectionHigh

Slider.SelectionHigh = longSelHigh

Element | Description
longSelHigh | A value that indicates the high value of the selection range.

Remarks

The value for the SelectionHigh property must be within the MinRange and MaxRange properties and greater than the SelectionLow property.


StaticEdge Property (Slider)

StaticEdge Property

The StaticEdge property sets or gets whether the Slider has a static edge.

Syntax

bMode = Slider.StaticEdge

Slider.StaticEdge = bMode

Element | Description
bMode | True indicates that a static edge is used; False indicates that it is not.

Remarks

Affects the appearance of the Slider.


TickFrequency Property

The TickFrequency property gets or sets a value that indicates the spacing of the ticks on the Slider.

Syntax

longFreq = Slider.TickFrequency

Slider.TickFrequency = longFreq

Element | Description
longFreq | A value that determines the spacing of the ticks.

Remarks

This value determines the spacing of the ticks. For example, with a MinRange = 0 and a MaxRange = 100, setting TickFrequency = 20 would give 5 divisions with 6 tick marks total. For even tick spacing, the (MaxRange-MinRange)/TickFrequency should be a whole number.


Ticks Property

The Ticks property sets or gets whether the slider displays tick marks.

Syntax

bMode = Slider.Ticks

Slider.Ticks = bMode

Element | Description
bMode | True indicates that ticks are shown; False indicates that no ticks are shown.

Remarks

Affects the appearance of the Slider.


Transparent Property (Slider)

Transparent Property

The Transparent property sets or gets a value that determines whether the control “underneath” is visible.

Syntax

bMode = Slider.Transparent

Slider.Transparent = bMode

Element | Description
bMode | True indicates that the Slider is transparent; False indicates that it is solid.


Recalculate Method (Slider)

Recalculate Method

The Recalculate method recalculates the control.

Syntax

Slider.Recalculate()

Remarks

Use within the framework of the Mathcad worksheet to force the scripted object to recalculate. This fires the Start, Exec, and Stop events. This method can be called from within events the control might listen for, including the ValueChanged event. After the Slider control recalculates, any dependent expressions in the Mathcad worksheet will also update if AutoCalculate is on.


ValueChanged Event

The ValueChanged event is fired when the Sliders pointer has changed position.

Syntax

Private Sub Slider_ValueChanged()

Remarks

This is the only event the Slider control handles. In this event handler, you commonly would call the Recalculate method. In your Exec event, you would retrieve the current value of the Position property as an output.


Using Controls Together

Mixing Types of Controls in One Worksheet

In your use of controls, it is very likely that you will find it interesting or necessary to mix them in your worksheets. For example, you might find that you want the user to select from among choices in a list box and specify some numerical parameters directly using either a slider or a text box. Sometimes, you may want to use these controls interdependently such that output from one control is used as input from another control.

Here is an annotated example that shows controls being used together in a worksheet. Other worksheets containing controls are located in the qsheet\Samples\Controls subdirectory of your installation of Mathcad.

Scripts

List Box

Rem Initialize List Box
ListBox.ResetContent()
ListBox.AddString("Addition")
ListBox.AddString("Subtraction")
ListBox.AddString("Multiplication")
ListBox.AddString("Division")
ListBox.CurSel = 0

Sub ListBoxEvent_Start()
Rem TODO: Add your code here
End Sub

Sub ListBoxEvent_Exec(Inputs,Outputs)
Outputs(0).Value = ListBox.CurSel + 1
End Sub

Sub ListBoxEvent_Stop()
Rem TODO: Add your code here
End Sub

Text Box

Sub TextBoxEvent_Start()
TextBox.Text="Choose an operation"
TextBox.Multiline = True
operation = Worksheet.getValue("op")
If operation=1 Then
TextBox.Text="Performing addition"
ElseIf operation=2 Then
TextBox.Text="Performing subtraction"
ElseIf operation=3 Then
TextBox.Text="Performing multiplication"
Else
TextBox.Text="Performing division"
End If
End Sub

Sub TextBoxEvent_Exec(Inputs,Outputs)
Rem TODO: Add your code here
End Sub

Sub TextBoxEvent_Stop()
Rem TODO: Add your code here
End Sub

How It Appears in the Worksheet

list box and text box

Comments

The list box control generates an index variable, 1 through 4, and then that value is used as input to the text box control, which reports the operation selected using a simple If... Then... Else construct. In particular, note that the script calls the worksheet variable, “op”, directly, accessing its value through Mathcad’s Automation interface.

To make this set of controls more streamlined looking in your worksheet, it is a good idea to hide the arguments. Right click the control and select Hide Arguments from the popup menu. Here is the sample worksheet with the arguments hidden:

list box and text box

Notes

Controls follow the same dependency protocols as any other regions in the worksheet. Therefore, you may use the outputs from one control as the inputs to another control, as long as the dependent control is to the right or below the control upon which it is dependent.

Sample File

Here is a sample file that demonstrates the example above.

Launch QuickSheet Example


Exporting a Control

Once you have created and customized a control, you can export it for reuse in another worksheet, saving both your script and any properties you may have set. An exported control can be inserted directly from the Component Wizard.

To export your control as a component, perform the following steps:

  • Right click on the control you wish to export, and choose Export as Component.
  • In the resulting dialog, specify a name and a location for your control.
  • Click "Next".
  • If you wish to protect the script for your control so that it cannot be edited when inserted in a worksheet, specify and confirm a password.
  • Click "Finish".

The control is exported as an MCM file to the location you set and automatically registered. From this point on, you can reuse the control simply by selecting it in the Component Wizard. MCM files can also be shared with other users. To import an MCM file you receive from another user, double click on the file to register it. We recommend that you save your MCM files to a common location, such as the mcm directory in your Mathcad installation.

By exporting customized controls, you can create your own toolkit of solutions to common problems you might face.


Automation in Scriptable Objects

A Scriptable Object may access Mathcad’s Automation interface in its script. Specifically, you can refer to worksheet variables — numbers, strings, arrays — directly, and you can get and set properties and call methods of the worksheet, the application, and the window.

Simple Annotated Example

Here is an annotated example that shows how a button can be used to enable and disable Automatic Calculation in the active worksheet. Other worksheets containing controls are located in the qsheet\Samples\Controls subdirectory of your installation of Mathcad.

Script

Dim state

Sub PushBtnEvent_Start()
Rem TODO: Add your code here
End Sub

Sub PushBtnEvent_Exec(Inputs,Outputs)
End Sub

Sub PushBtnEvent_Stop()
Rem TODO: Add your code here
End Sub

Sub PushBtn_Click()
If state = 0 Then
state = 1
PushBtn.Flat = 1
PushBtn.Text = "Auto Calculation is OFF"
Worksheet.SetOption mcAutocalc, False
Else
state = 0
PushBtn.Flat = 0
PushBtn.Text = "Auto Calculation is ON"
Worksheet.SetOption mcAutocalc, True
End If

PushBtn.Recalculate()
End Sub

How It Appears in the Worksheet

list box and text box

Comments

The Worksheet object supports a SetOption method, an option of which is enabling and disabling Automatic Calculation. The state and appearance of the button is set in the script, too, but these settings may also be adjusted in the Properties dialog box.

Other worksheet actions you might want to automate in a button include printing a worksheet, recalculating a worksheet, and saving a worksheet. These are all methods supported in the Worksheet class.

Sample File

Here is a sample file that demonstrates Automation in Mathsoft Controls.

Launch QuickSheet Example


Scripting

Scripting OLE Automation Objects in Mathcad

Mathcad exposes a component that allows you to embed an ActiveX control in the worksheet and call its Automation interface for use within the Mathcad computational environment. This component uses the Microsoft ActiveX Scripting specification, allowing you to use standard scripting languages to automate the object. While these languages allow you to communicate with the OLE object, they do not have any intrinsic facilities for communicating with the outside environment (in this case, Mathcad). For a scripted object to be useful in a computation, it must have a mechanism for processing inputs and sending outputs to and from the host environment. The Scriptable Object component solves this problem by providing a framework for scripting languages to interact with Mathcad.

Note:

In the Help pages that follow, Mathcad may be referred to as the host environment, as opposed to the scripted object which contains that embedded control.


Overview of Events

The scripting component has adopted an event-driven model to serve as the framework for scripting components. This model defines three basic events, Start, Exec and Stop, which are triggered by the outside (host) environment. These events are discussed in the following sections.

Event-Driven vs. Procedural

Most programming languages are structured to be executed as a series of statements: either in a top-down fashion starting with the first statement encountered, or with a predefined entry point (such as main() in the C language). This procedural approach assumes a program which will be carried out linearly, continuously executing statements until the last statement is reached. While this works well in a variety of contexts, it is not as useful in an environment which is event-driven. In an event-driven environment, the program is called upon to do work based on the triggering of an outside event. This is typically accomplished by defining one or more event functions which are called by the event controller whenever an appropriate event is triggered.

Object-oriented programming is generally event-driven. In Mathcad, when you script an object through the Scriptable Object component, you are scripting behavior based on events that take place in the object. For example, you might program output to be sent to the Mathcad worksheet once a certain threshold has been reached in an external calculation or process.


Start Event

The Start event is executed by the host environment whenever a computation is started. This is a good place for scripts to set initialization variables, open files for reading or writing, etc.

In this sample, the object is a slider control and its appearance and initial settings are being programmed in the Start event.

Example VBScript code:

Sub SliderEvent_Start()

Slider.MinRange = –10

Slider.MaxRange = 10

Slider.TickFrequency = 1

Slider.StaticEdge = False

Slider.ClientEdge = False

End Sub

Note:

In the MathConnex environment, the Start event is executed once when the component is initialized in the host environment. The Start event will not recalculate again even if inputs to the component change and force recalculation of the Exec event.


Exec Event

This event is executed when the host environment supplies inputs and requests any outputs from the script. There are two parameters defined for the Exec function: Inputs and Outputs. These parameters are objects of type DataValue. See DataValues Collection for details.

In this sample, the object is a slider control and its output is being programmed in the Exec event.

Example VBScript code:

Sub SliderEvent_Exec(Inputs,Outputs)

Outputs(0).Value = Slider.Position

End Sub

Note:

In the MathConnex environment, it is possible for this event function to be called many times after a single Start event is triggered. Script writers should put any "one-time" initialization code in the Start event so that the script is able to handle repeated calls to Exec for processing of input and output data.


Stop Event

This event is executed to tell the script that the current computation has stopped. It will only be called after the Start event has been called. This is a good place for cleanup of data, closing any open files, etc.

Note:

It is possible for the Start and Stop event to be triggered one after the other without the Exec event ever being triggered. This can happen in cases where the computation begins but the input data is never available to the script component, preventing it from executing.


Event Function Implementation

The actual event function syntax is language-specific. Most scripting languages provide a standard mechanism for event functions, usually a combination of the object which defines the event (sometimes referred to as the object that “sources” the event) and the name of the event. When a script contains a function that matches the naming convention used for the event, the language “attaches” the function to the event so that it is called whenever the event is fired. VBScript, for example, uses the name of the event source, followed by an underscore, followed by the event name. So if an object called "MyEventSrc" defined an event handler called "Event1", then the VBScript function would look something like this:

Sub MyEventSrc_Event1( )

' do something when the event is triggered

End Sub

The event functions are defined in an OLE object’s type library. The script writer must be aware that the events exist and the names used for them in order to provide appropriate event handler functions in the script.

For example, the events defined for Mathsoft Controls are listed in this reference and describe all available triggers for calculating with these controls.


Introduction to the Scripting Object Model

The following topics detail all methods, properties, and events exposed for scripts written with the Scriptable Object component. For convenience, the examples use VBScript style syntax unless otherwise noted.

The Scripting Model is fairly abbreviated as the component itself is really just a container for an object performing operations outside the host environment. As such, the methods, properties and events are largely in place to support sending data in and out of the component from the worksheet.


alert Function

This function is provided mainly for compatibility with the JScript language. This function takes a single parameter as a string which will be presented to the user as a standard modal Windows message box with an OK button.

Syntax

alert(string)

Element | Description
string | The message you wish to display in the alert dialog.

Remarks

VBScript users will probably want to use the more extensive MsgBox function — which is provided natively by the VBScript engine — rather than the alert method.

Example Code

function MyEventSrc::Event1( )

{

// will pop up a message box with the following text

alert("In MyEventSrc_Event1!");

}

Note:

The example above uses the JScript language syntax.


Introduction

Collections are an Automation concept that allows a set of associated elements to be bundled together. Standard methods and properties are provided to allow access to each of the elements in the collection. Collections are directly supported in some languages, allowing easy iteration over the elements in the collection. VBScript supports collections through the For Each...Next construct. Languages that do not directly support collections can still iterate through the elements using the standard properties and methods described below.

The DataValues collection is used in the Exec event, which has two DataValues collections as parameters. The first parameter (named “Inputs”) is a collection of inputs. Each input element in the collection is an object of type DataValue. Script authors can iterate through elements and query the total number of elements in the collection. The “Outputs” parameter is also a collection of DataValue objects representing each output provided by the component. Script authors may set the data for each output object in the collection. These output values are then used by the host environment when the event function returns.


Count Property

The read-only Count property can be used to query the total number of elements in the collection.

Syntax

num = collDataValues.Count

Element | Description
num | Number of items in the DataValues collection

Remarks

Note that the collection is zero based.

Example Code

'cycle through the collection, assigning each item to a variable

for i=0 to Inputs.Count–1

val = Inputs(i)

'additional code...

next


Item Method

The Item method is used to specify an individual element in the collection. The DataValues collection is zero-based, so the item numbers range from 0 to Count–1.

The Item method is the default method for this object; for languages that support it, this means that the method name can be omitted, in which case the default method is implied.

Syntax

collDataValues.Item( index )

collDataValues( index )

Element | Description
index | The index of the item to retrieve.

Remarks

Note that the DataValues collection is zero based.

Example Code

'retrieve each item from the collection

for i=0 to Inputs.Count–1

val = Inputs.Item(i)

'additional code

next

or, since Item is the default property, the following is also valid:

for i=0 to Inputs.Count–1

val = Inputs(i)

next

Note:

Although the example above shows VBScript, both VBScript and JScript support this shorthand approach for default methods and properties.


Value Property

The Value property is used to access the real portion of the data in the DataValue object.

Syntax

x = objDataValue.Value ( [row, col] )

objDataValue.Value ( [row, col] ) = x

Element | Description
x | The real portion of the data at this position.
row | The index of the desired row.
col | The index of the desired column.

Remarks

Note that the row and col parameters are optional. If the row and col parameters are omitted, then the value is returned as a 2D variant array of double values or as a 1D variant array of double values or as a scalar, depending on the type of data contained in the DataValue object. If the row and col parameters are specified, a scalar value at the specified row/column is returned.

When the Value property is used on the left hand side of an assignment, the array automatically grows (if necessary) to fit the data. For example, if Outputs(0) initially contains no data and the script writer does the following:

Outputs(0).Value(1,2) = 1

a 2 row, 3 column data value is created which contains the value “1” at row 1, col 2. If a value already exists and an assignment is made which exceeds the current maximum row or column, the value is automatically re-dimensioned to fit the new data. This feature of the Value property allows languages that do not directly support variant arrays (such as JScript) to create and access DataValue arrays.

Example Code

for i=0 to Inputs.Count–1

valmatrix = Inputs(i).Value ' returns a whole matrix

valscalar = Inputs(i).Value(0,0) ' returns element at 0,0

next


IValue Property

The IValue property is used to access the imaginary portion of the data in the DataValue object.

Syntax

x = objDataValue.IValue ( [row, col] )

objDataValue.IValue ( [row, col] ) = x

Element | Description
x | The imaginary portion of the data at this position.
row | The index of the desired row.
col | The index of the desired column.

Remarks

Note that the row and col parameters are optional. If the row and col parameters are omitted, then the value is returned as a 2D variant array of double values or as a 1D variant array of double values or as a scalar, depending on the type of data contained in the DataValue object. If the row and col parameters are specified, a scalar value at the specified column/row representing the imaginary portion of the data is returned. Note that the DataValue object may not contain an imaginary value (e.g. it is a real number), in which case the IValue portion will return NIL.

Example Code

for i=0 to Inputs.Count–1

valmatrix = Inputs(i).IValue ' returns a whole matrix

if (valmatrix != nil) then

valscalar = Inputs(i).IValue(1,0) ' returns element

end if

next


Rows Property

The Rows property is a read-only value which returns the number of rows in the DataValue object.

Syntax

x = objDataValue.Rows

Element | Description
x | The number of rows in the DataValue object.

Remarks

Can be used to determine the dimensions of a vector of array stored at a particular element at run-time. This provides flexibility and allows the programmer to avoid hard-coding a fixed number of rows.

Example Code

NumRows = Inputs(0).Rows


Cols Property

The Cols property is a read-only value which returns the number of columns in the DataValue object.

Syntax

x = objDataValue.Cols

Element | Description
x | The number of columns in the DataValue object.

Remarks

Can be used to determine the dimensions of a vector of array stored at a particular element at run-time. This provides flexibility and allows the programmer to avoid hard-coding a fixed number of columns.

Example Code

NumRows = Inputs(0).Cols


IsComplex Property

The IsComplex property is a read-only value which returns TRUE if the value has a valid imaginary portion (which can be accessed through the IValue property). If IsComplex returns FALSE, it can be assumed that the value has only a real portion.

Syntax

bool = objDataValue.IsComplex

Element | Description
bool | Returns TRUE if data object has a valid imaginary part; otherwise returns FALSE.

Remarks

This property could be used to filter complex data from a data set.

Example Code

'check a particular input and inform the user whether complex or real

if (Inputs(0).IsComplex ) then

MsgBox( "Complex Value!" )

else

MsgBox( "Real Value!" )

end if


Script Examples Introduction

Introduction to Script Examples

The following sections show sample scripts using VBScript and JScript within a Mathcad component. Note that these examples are intended to give an impression of the syntactical conventions and how they apply to various object methods and properties, rather than a truly useful script.

The scripts below both accomplish the same task. They iterate through the available inputs, display the value of the first element in a popup message box, assign the input to the output, and finally add one to the first element of each output.


VBScript Examples

This version of the script will iterate through each available input using the For Each...Next construct.

Sub ScriptObjEvent_Start()
'Add your code here
End Sub

Sub ScriptObjEvent_Exec(Inputs,Outputs)

Dim i
Dim dataval
i=0

'loop through Inputs collection
For each dataval in Inputs

'extract value of this particular Input
val = dataval.Value

'pop up a message box to show progress through collection, using
'only upper left element of array
If IsArray(val) Then
MsgBox "Input: " & CStr(i) & " is an array"
Else
MsgBox "Input: " & CStr(i) & ", Value: " & CStr(val)
End If

'just pass inputs to the outputs, incrementing
'the first element at 0,0 position by 1
If i < Outputs.Count Then
If IsArray(val) Then
On Error Resume Next
vTemp = UBound(val,2)
If Err.Number = 0 Then
val(0,0) = val(0,0) + 1
Else
val(0) = val(0) + 1
End If
Else
val = val + 1
End If
Outputs(i).Value = val
End If
i = i + 1
Next

End Sub

Sub ScriptObjEvent_Stop()
'Add your code here
End Sub

The second version accomplishes the same task without using the For Each...Next construct:

Sub ScriptObjEvent_Start()
'Add your code here
End Sub

Sub ScriptObjEvent_Exec(Inputs,Outputs)
Dim dataval

'use for/next construct to loop over inputs
for i=0 to Inputs.Count-1

'get the current input and its value
set dataval = Inputs(i)
val = dataval.Value

'pop up a message box to show progress through collection
MsgBox(val(0,0))

'just pass inputs on to the outputs, incrementing
'the first element by 1
if i < Outputs.Count then
val(0,0) = val(0,0)+1
Outputs(i).Value = val
end if
next
End Sub

Sub ScriptObjEvent_Stop()
'Add your code here
End Sub


JScript Examples

The JScript version of the VBScript Examples is shown below.

function ScriptObjEvent::Start()
{
// TODO: Add code here
}

function ScriptObjEvent::Exec(inputs,outputs)
{
var dataval;
for ( i=0; i<Inputs.Count; i++ )

// look at each dataval in the collection
dataval = Inputs(i)

// show what we found
alert("Input: " + i.toString() + ", Value: " + dataval.Value(0,0).toString());

// pass inputs on to outputs, incrementing
// first element by one
if ( i<Outputs.Count )
{
Outputs(i).Value = dataval.Value;
Outputs(i).Value(0,0) += 1 ;
}

}

function ScriptObjEvent::Stop()
{
// TODO: Add code here
}


Exporting a Component

Once you have created and customized a component, you can export it for reuse in another worksheet, saving your script. An exported component can be inserted directly from the Component Wizard.

To export your component, perform the following steps:

  • Right click on the component you wish to export, and choose Export as Component.
  • In the resulting dialog, specify a name and a location for your component.
  • Click "Next".
  • If you wish to protect the script for your component so that it cannot be edited when inserted in a worksheet, specify and confirm a password.
  • Click "Finish".

The component is exported as an MCM file to the location you set and automatically registered. From this point on, you can reuse the component simply by selecting it in the Component Wizard. MCM files can also be shared with other users. To import an MCM file you receive from another user, double-click on the file to register it. We recommend that you save your MCM files to a common location, such as the mcm directory in your Mathcad installation.

By exporting customized components, you can create your own toolkit of solutions to common problems you might face.


Using Mathcad's OLE Automation Interface

Mathcad's OLE Automation interface provides a mechanism for communicating with Mathcad from within another Windows application. (If you are interested instead in scripting an OLE object within the Mathcad or MathConnex environment, see the section on Scripting Custom OLE Objects) Using OLE Automation, you can send data to Mathcad from another application, use Mathcad to perform calculations or other data manipulations, and send results back to the original application. With Mathcad 5 and 6, this kind of communication was carried out using DDE (dynamic data exchange). In Mathcad 7.02 and higher versions, DDE has been superseded by OLE Automation.

To use OLE Automation technology, you must write a program in Visual Basic 5.0 (or higher) or in an application that can serve as an OLE Automation client, such as Microsoft Excel version 5.0 (or higher). Check with the application's documentation to find out if it can serve as an OLE Automation client. The program defines and retrieves variables in Mathcad Document objects. The variables defined in Mathcad must be named in0, in1, in2, myVariable, etc. and the number of inputs to the Mathcad Document object is virtually unlimited. The variables being retrieved from Mathcad must be called out0, out1, out2, etc. and the number of outputs is limited to ten (i.e. out0-out9 are the only allowable values).

Mathcad provides two APIs: an API for embedded objects and a scripting API.


Automation Overview

The Automation API can be used with Mathcad 2001i and higher. It consists of a hierarchy of automation classes, each with their own properties, methods, and events. The Automation API utilizes an expanded object model, providing control over the appearance of the Mathcad object and access to actions available from menu items and toolbar buttons.

The Application Class can be invoked by CoCreating an instance of Mathcad.Application. Additionally, the Worksheet Class can be invoked directly by CoCreating an instance of Mathcad.Worksheet.

Classes and Collections

  • Application Class
  • Worksheets Collection
  • Worksheet Class
  • Window Class
  • Region Class
  • NumericValue Class
  • StringValue Class
  • MatrixValue Class


Mathcad Automation Interface Enumerations

IMathcadApplication Interface Enumerations

The Mathcad Automation interface includes several enumerations to make it easier for you to use certain Mathcad features within another application. In order to use these enumerations, you must first import the Mathcad type library (automation.dll). If you are developing in Visual Basic, the enumerations are available in the Mathcad Automation 1.0 Type Library.

Enumerations

Name | Description
MCFileFormat | Specifies the file format in the various places where the Worksheet object can be saved.
MCRegionType | Indicates the type of Region object.
MCSaveOption | Specifies the action to take when closing files which have been modified.
MCWindowState | Indicates the window state of a Window object.
MCWorksheetOption | Specifies a Worksheet-level option.


MCFileFormat Enumeration

The MCFileFormat enumeration specifies the file format in the various places where a worksheet can be saved.

Name | Value | Description
mcDefaultFormat | 0 | Whichever format the worksheet was loaded in as.
mcPromptUser | 1 | Allow the user to pick from a list of available formats.
mcHTML | 2 | Static HyperText Markup Language page.
mcMathML | 3 | HTML/MathML for IBM techexplorer.
mcMcad6 | 4 | Mathcad 6 worksheet.
mcMcad7 | 5 | Mathcad 7 Worksheet.
mcMcad8 | 6 | Mathcad 8 Worksheet.
mcMcad2000 | 7 | Mathcad 2000 worksheet.
mcMcad2001 | 8 | Mathcad 2001 worksheet.
mcMcadCurrentVersion | 9 | Current Mathcad version format.
mcTemplate | 10 | Mathcad Template.


MCRegionType Enumeration

The MCRegionType enumeration indicates the type of a Region object.

Name | Value | Description
mcTextRegion | 0 | Text Region.
mcMathRegion | 1 | Math (equation) region.
mcBitmapRegion | 2 | Bitmap Region.
mcMetafileRegion | 3 | Metafile Region.
mcOLERegion | 4 | OLE object Region.


MCSaveOption Enumeration

The MCSaveOption enumeration specifies the possible options to take when closing files which have been modified.

Name | Value | Description
mcSaveChanges | 0 | Automatically save changes in whichever format the Worksheet was loaded in as.
mcPromptToSaveChanges | 1 | Ask user whether or not to save a worksheet.
mcDiscardChanges | 2 | Lose changes.


MCWindowState Enumeration

The MCWindowState enumeration specifies the possible states of a Window object.

Name | Value | Description
mcMaximized | 0 | The window is maximized.
mcMinimized | 1 | The window is minimized (iconified).
mcNormal | 2 | The window is resizable.


MCWorksheetOption Enumeration

The MCWorksheetOption enumeration specifies .

Name | Type | Description
mcAutoRecalc | bool | Toggles Automatic Recalculation on and off.


Application Class

The Application Class encompasses the following properties, methods, and events:

Properties

  • ActiveWindow
  • ActiveWorksheet
  • Application
  • DefaultFilePath
  • FullName
  • Name
  • Parent
  • Path
  • Version
  • Visible
  • Windows
  • Worksheets
  • Top
  • Width
  • Height
  • Left

Methods

  • CloseAll
  • Quit

Events

  • Quit
  • WindowActivated
  • WindowDeactivated
  • WorksheetClosing
  • WorksheetOpened


ActiveWindow Property

The ActiveWindow property gets the currently active window.

Syntax

bMode = objMC.ActiveWindow

Element | Description
bMode | Returns the currently active window. Returns NULL if no windows are active.
objMC | A Mathcad application object.


ActiveWorksheet Property

The ActiveWorksheet property gets the worksheet of the currently active window.

Syntax

bMode = objMC.ActiveWorksheet

Element | Description
bMode | Returns the Worksheet object displayed in the currently active window. Returns NULL if no windows are active.
objMC | A Mathcad application object.

Remarks

This property is equivalent to calling objMC.ActiveWindow.Worksheet.


Application Property (Application Class)

Application Property

The Application property gets the application which owns the Application object.

Syntax

bMode = objMC.Application

Element | Description
bMode | Returns the application which owns the Application object.
objMC | A Mathcad application object.


DefaultFilePath Property

The DefaultFilePath property gets or sets the default path for opening and saving worksheets.

Syntax

bStr = objMC.DefaultFilePath

objMC.DefaultFilePath = bStr

Element | Description
bStr | A string containing the default path for opening and saving worksheets.
objMC | A Mathcad application object.


FullName Property (Application Class)

FullName Property

The FullName property gets the path and name of the Mathcad application.

Syntax

bStr = objMC.FullName

Element | Description
bStr | A string containing the full path to the Mathcad executible, including the .exe extension.
objMC | A Mathcad Application object.


Height Property (Application Class)

Width Property

The Height property gets or sets the height, in pixels, of the main application window.

Syntax

uLong = objMC.Height

objMC.Height = uLong

Element | Description
uLong | Height, in pixels, of the main application window. Expressed as an unsigned long.
objMC | A Mathcad Application object.


Left Property (Application Class)

Left Property

The Left property gets or sets the distance, in pixels, of the main application window from the left edge of the screen.

Syntax

uLong = objMC.Left

objMC.Left = uLong

Element | Description
uLong | Distance, in pixels, of the main application window from the left edge of the screen. Expressed as an unsigned long.
objMC | A Mathcad Application object.


Name Property (Application Class)

Name Property

The Name property gets the name of the application that owns an Application object.

Syntax

bMode = objMC.Name

Element | Description
bMode | Returns the application which owns the Application object.
objMC | A Mathcad Application object.


Parent Property (Application Class)

Parent Property

The Parent property gets the parent of an Application object.

Syntax

bMode = objMC.Parent

Element | Description
bMode | Returns the parent of the Application object.
objMC | A Mathcad application object.


Path Property (Application Class)

Path Property

The Path property gets the path to the Mathcad application.

Syntax

bStr = objMC.Path

Element | Description
bStr | A string containing the path to the Mathcad executable.
objMC | A Mathcad Application object.


Top Property (Application Class)

Top Property

The Top property gets or sets the distance, in pixels, of the main application window from the top of the screen.

Syntax

uLong = objMC.Top

objMC.Top = uLong

Element | Description
uLong | Distance, in pixels, of the main application window from the top of the screen. Expressed as an unsigned long.
objMC | A Mathcad application object.


Version Property

The Version property gets the application's version number as a string.

Syntax

bStr = objMC.Version

Element | Description
bStr | The version number of Mathcad, returned as a string.
objMC | A Mathcad Application object.


Visible Property

The Visible property gets or sets visibility of the main Mathcad window.

Syntax

bool = objMC.Visible

objMC.Visible = bool

Element | Description
bool | Boolean value indicating whether the main application window will be visible or not. True indicates that the window will be visible; False indicates that the it will not.
objMC | A Mathcad application object.


Width Property (Application Class)

Width Property

The Width property gets or sets the width, in pixels, of the main application window.

Syntax

uLong = objMC.Width

objMC.Width = uLong

Element | Description
uLong | Width, in pixels, of the main application window. Expressed as an unsigned long.
objMC | A Mathcad application object.


Windows Property (Application Class)

Windows Property

The Windows property gets the collection of Window objects representing all open Mathcad worksheet views.

Syntax

bMode = objMC.Windows

Element | Description
bMode | Collection of Window objects representing all open worksheet views.
objMC | A Mathcad Application object.


Worksheets Property

The Worksheets property gets the collection of Worksheet objects representing all open Mathcad worksheets.

Syntax

bMode = objMC.Worksheets

Element | Description
bMode | The collection of Worksheet objects.
objMC | A Mathcad application object.


CloseAll Method

The CloseAll method closes all open worksheets.

Syntax

boolRet = objMC.CloseAll MCSaveOption SaveOption

Element | Description
boolRet | Return value indicating success or failure.
objMC | A Mathcad application object.
MCSaveOption | Optional argument specifying how to handle unsaved worksheets. The default is McPromptToSaveChanges.

Remarks

The CloseAll method can fail if the save failed to complete for any reason, such as insufficient disk space or cancelling out of the save operation.

Example

The following Visual Basic code demonstrates usage of the CloseAll method. If the optSave flag has been set (in this case, via user interaction), the CloseAll method is invoked with the corresponding argument enumerated in MCSaveOption.

Select Case optSave

Case None

'Default option

objMathcadApp.CloseAll

Case Lose

'Lose Changes

objMathcadApp.CloseAll mcDiscardChanges

Case Prompt

'Ask user whether to save

objMathcadApp.CloseAll mcPromptToSaveChanges

Case Save

'save changes

objMathcadApp.CloseAll mcSaveChanges

Case Else

'invalid options - unsuccessful closing of worksheets

MsgBox ("Close Failed")

End Select


Quit Method

The Quit method ends the particular Mathcad session and optionally saves any open worksheets.

Syntax

objMC.Quit MCSaveOption SaveOption

Element | Description
objMC | A Mathcad application object.
MCSaveOption | Optional argument specifying how to handle unsaved worksheets. The default is McPromptToSaveChanges.

Remarks

This method returns no meaningful result.


Quit Event

The Quit event signals that the application is ending.

Element | Description
Event | Quit
Description | The application is exiting.
Parameters | None.


WindowActivated Event

The WindowActivated event signals that a window has just been activated.

Element | Description
Event | WindowActivated
Description | A window has just been activated.
Parameters | [out] Window ** Worksheet The window that has just been activated.


WindowDeactivated Event

The WindowDeactivated event signals that a window has just been deactivated.

Element | Description
Event | WindowDeactivated
Description | A window has just been deactivated.
Parameters | [out] Window ** Worksheet The window that has just been deactivated.


WorksheetClosing Event

The WorksheetClosing event signals that a worksheet is about to close.

Element | Description
Event | WorksheetClosing
Description | A worksheet is about to close.
Parameters | [out] Worksheet ** Worksheet The worksheet that is closing.


WorksheetOpened Event

The WorksheetOpened event signals that a worksheet has just been opened.

Element | Description
Event | WorksheetOpened
Description | A worksheet has just been opened.
Parameters | [out] Worksheet ** Worksheet The worksheet that has just been opened.


Worksheets Collection

The Worksheets Collection is a standard OLE automation collection whose items are Worksheet objects, indexed by position (number) and name (string). The interface encompasses the following properties and methods:

Properties

  • Application
  • Parent

Methods

  • Open


Application Property (Worksheets Collection)

Application Property

The Application property gets the application which owns a collection of Worksheet objects.

Syntax

bMode = objMC.Application

Element | Description
bMode | The application which owns the specified Worksheet Collection.
objMC | A Mathcad worksheet collection.


Parent Property (Worksheets Collection)

Parent Property

The Parent property gets the parent of a collection of Worksheet objects.

Syntax

bMode = objMC.Parent

Element | Description
bMode | The parent of the Worksheet collection.
objMC | A Mathcad worksheet collection.


Open Method

The Open method opens the specified worksheet. It will not open handbooks.

Syntax

bMode = objMC.Open(FileSpec As String)

Element | Description
bMode | The Worksheet object opened.
objMC | A Mathcad worksheet collection.
FileSpec | Argument specifying the path to worksheet being opened.


Worksheet Class

The Worksheet class encompasses the following properties and methods supported by the Worksheet object:

Properties

  • Application
  • FullName
  • Name
  • NeedsSave
  • Options
  • Parent
  • Path
  • Regions
  • Windows

Methods

  • Close
  • GetOption
  • GetValue
  • PrintAll
  • Recalculate
  • Save
  • SaveAs
  • SetOption
  • SetValue

Events

  • Changed
  • Recalculated


Application Property (Worksheet Class)

Application Property

The Application property gets the application which owns a Worksheet object.

Syntax

bMode = objMC.Application

Element | Description
bMode | Returns the application which owns the current Worksheet object.
objMC | A Mathcad Worksheet object.


FullName Property (Worksheet Class)

FullName Property

The FullName property retrieves the fully-qualified path to the worksheet.

Syntax

bStr = objMC.FullName

Element | Description
bStr | A string containing the fully-qualified path to the Mathcad worksheet.
objMC | A Mathcad Worksheet object.


Name Property (Worksheet Class)

Name Property

The Name property gets the name of the worksheet.

Syntax

bStr = objMC.Name

Element | Description
bStr | The worksheet's filename, without the extension. The filename can only be changed through the SaveAs method.
objMC | A Mathcad Worksheet object.


NeedsSave Property

The NeedsSave property gets whether the worksheet has been changed and needs to be saved. NeedsSave is reset to False upon saving the worksheet.

Syntax

bool = objMC.NeedsSave

Element | Description
bool | Boolean value indicating whether or noot the worksheet has been changed and needs to be saved.
objMC | A Mathcad Worksheet object.


Options Property

The Options property gets or sets options in a Worksheet object.

Syntax

variant = objMC.Options(MCWorksheetOption WorksheetOption)

objMC.Options(MCWorksheetOption WorksheetOption) = variant

Element | Description
variant | The worksheet option to set or return. The content of variant varies with the option type.
objMC | A Mathcad Worksheet object.
MCWorksheetOption | The worksheet option to send to or return from Mathcad.


Parent Property (Worksheet Class)

Parent Property

The Parent property gets the parent of a Worksheet object.

Syntax

bMode = objMC.Parent

Element | Description
bMode | The parent of the Worksheet object.
objMC | A Mathcad Worksheet object.


Path Property (Worksheet Class)

Path Property

The Path property gets the path to the worksheet, without the filename.

Syntax

bStr = objMC.Path

Element | Description
bStr | A string containing the path to the worksheet.
objMC | A Mathcad Worksheet object.


Regions Property

The Regions property gets a collection of Region objects from the Worksheet object.

Syntax

bMode = objMC.Regions

Element | Description
bMode | Returns a collection of Region objects from the Worksheet object, representing Mathcad regions within the worksheet.
objMC | A Mathcad Worksheet object.


Windows Property (Worksheets Collection)

Windows Property

The Windows property gets a collection of Window objects from the Worksheet object.

Syntax

bMode = objMC.Windows

Element | Description
bMode | Returns a collection of Window objects from the Worksheet object, representing the views associated with the worksheet.
objMC | A Mathcad Worksheet object.


Close Method

The Close method closes the open Worksheet object.

Syntax

objMC.Close MCSaveOption SaveOption

Element | Description
objMC | A Mathcad worksheet object.
MCSaveOption | Optional argument specifying how to handle unsaved worksheets. The default is McPromptToSaveChanges.

Remarks

This method returns no meaningful result.

The Close method can fail if the save failed to complete for any reason, such as insufficient disk space or cancelling out of the save operation.


GetOption Method

The GetOption method returns the current value of the specified worksheet option.

Syntax

variant = objMC.GetOption( MCWorksheetOption Option)

Element | Description
variant | Returns the current value of the specified worksheet option. The content of variant varies with the option type.
objMC | A Mathcad application object.
MCWorksheetOption | The option to query Mathcad for.


GetValue Method

The GetValue method returns the value bound to a symbolic name in the Worksheet object. The binding returned is the bottom-most binding in the worksheet.

Syntax

VT_DISPATCH = objMC.GetValue(Name As String)

Element | Description
VT_DISPATCH | A value object.
objMC | A Mathcad worksheet object.
Name | The name of the variable to bind.

Remarks

The GetValue method can fail if the there is a problem finding the variable binding.


PrintAll Method

The PrintAll method prints the entire Worksheet object, using the default printer.

Syntax

objMC.PrintAll

Element | Description
objMC | A Mathcad application object.

Remarks

This method returns no meaningful result.


Recalculate Method (Worksheet Class)

Recalculate Method

The Recalculate property performs a recalculation of the active worksheet.

Syntax

objMC.Recalculate

Element | Description
objMC | A Mathcad worksheet object.

Remarks

This method returns no meaningful result.


Save Method

The Save method saves the Worksheet object.

Syntax

objMC.Save

Element | Description
objMC | A Mathcad application object.

Remarks

This method returns no meaningful result.

The Save method can fail if the save operation failed to complete for any reason, such as insufficient disk space or cancelling out of the save operation.


SaveAs Method (Worksheet Class)

SaveAs Method

The SaveAs method saves the Worksheet object with a new filename or in a different format.

Syntax

objMC.SaveAs(FileSpec As String, [MCFileFormat FileFormat])

Element | Description
objMC | A Mathcad application object.
FileSpec | The filename to save as.
MCFileFormat | Optional argument specifying which format to save the file as. The default is McDefaultFormat.

Remarks

This method returns no meaningful result.

The SaveAs method can fail if the save operation failed to complete for any reason, such as insufficient disk space or cancelling out of the save operation.


SetOption Method

The SetOption method sets the current value of the specified worksheet option.

Syntax

objMC.SetOption MCWorksheetOption Option, Value As Variant

Element | Description
objMC | A Mathcad application object.
MCWorksheetOption | The option to be set.
Value | The value of the option.

Remarks

This method returns no meaningful result.

The SetOption method can fail when used to set something other than a worksheet option.


SetValue Method

The SetValue method binds a value to a symbolic name in the Worksheet object. The binding takes place at the top of the worksheet, and any subsequent rebinding in the worksheet will replace the value. If AutoRecalc is set in the Worksheet object, the worksheet will be recalculated in its entirety whenever SetValue is called. If AutoRecalc is off, the automation client must use the Recalculate method to force a recalculation.

Syntax

objMC.SetValue(Name As String, Value As Variant)

Element | Description
objMC | A Mathcad application object.
Name | The name of the variable to bind.
Value | The value of the variable. The value may be any numeric or string variant type, a SAFEARRAY of any numeric or string variant type, a reference to a value object, or VT_NULL to remove the variable.

Remarks

This method returns no meaningful result.

The SetValue method can fail if there is a problem binding the variable.


Recalculated Event

The Recalculated event signals that the worksheet has been recalculated.

Element | Description
Event | Recalculated
Description | The worksheet has been recalculated.
Parameters | None.

Note:

This event is deprecated in Mathcad 11 and later.


Changed Event

The Changed event signals that the worksheet has been changed by in-place editing.

Element | Description
Event | Changed
Description | The worksheet has been edited.
Parameters | None.


Window Class

The Window class encompasses the following properties and methods:

Properties

  • Height
  • Left
  • Top
  • Width
  • WindowState
  • Zoom

Methods

  • Activate
  • ScrollTo
  • ScrollToRegion


Height Property (Window Class)

Height Property

The Height property gets or sets the height, in pixels, of the window.

Syntax

uLong = objMC.Height

objMC.Height = uLong

Element | Description
uLong | Height, in pixels, of the window.
objMC | A Mathcad Window object.


Left Property (Window Class)

Left Property

The Left property gets or sets the pixel position of the left side of the window relative to the main application window.

Syntax

uLong = objMC.Left

objMC.Left = uLong

Element | Description
uLong | Pixel position of the left side of the window relative to the main application window.
objMC | A Mathcad Window object.


Top Property (Window Class)

Top Property

The Top property gets or sets the pixel position of the top of the window relative to the main application window.

Syntax

uLong = objMC.Top

objMC.Top = uLong

Element | Description
uLong | Pixel position of the top of the window relative to the main application window.
objMC | A Mathcad Window object.


Width Property (Window Class)

Width Property

The Width property gets or sets the width, in pixels, of the window.

Syntax

uLong = objMC.Width

objMC.Width = uLong

Element | Description
uLong | Width, in pixels, of the window.
objMC | A Mathcad Window object.


WindowState Property

The WindowState property gets or sets the state of the worksheet window.

Syntax

MCWindowState = objMC.Zoom

objMC.Zoom = MCWindowState

Element | Description
MCWindowState | The enumerated window state.
objMC | A Mathcad Window object.


Zoom Property

The Zoom property gets or sets the magnification of the worksheet view, specified in percent of a Mathcad-determined refernce value. 100% is the default zoom. If not specified, Zoom returns the current zoom factor.

Syntax

uLong = objMC.Zoom

objMC.Zoom = uLong

Element | Description
uLong | Width, in pixels, of the window.
objMC | A Mathcad Window object.


Activate Method

The Activate method sbrings the window to the foreground and gives it the input focus..

Syntax

objMC.Activate

Element | Description
objMC | A Mathcad Window object.

Remarks

This method returns no meaningful result.


ScrollTo Method

The ScrollTo method scrolls the window to a specified page.

Syntax

bool = objMC.ScrollTo(X As uLong, Y As uLong)

Element | Description
bool | Return value indicating success or failure.
objMC | A Mathcad Window object.
X | Zero-based X-coordinate to scroll the window to, in logical document units.
Y | Zero-based Y-coordinate to scroll the window to, in logical document units.

Remarks

The origin for the X- and Y-coordinates used by the ScrollTo method is the upper left corner of the worksheet, and not the current window.


ScrollToRegion Method

The ScrollToRegion method scrolls the window to a specified region.

Syntax

bool = objMC.ScrollTo(Region As Reference)

Element | Description
bool | Return value indicating success or failure.
objMC | A Mathcad Window object.
Region | The region to scroll the window to.


Region Class

The Region Class represents a Mathcad region within a Worksheet object. It encompasses the following properties:

Properties

  • Tag
  • X
  • Y


Tag Property

The Tag property gets the text of a particular region's tag.

Syntax

bStr = objMC.Tag

Element | Description
bStr | The region tag. Tag returns a string.
objMC | A Mathcad Region object.


X Property

The X property gets the zero-based coordinate of the left edge of the region, in logical document units.

Syntax

uLong = objMC.X

Element | Description
uLong | The zero-based coordinate of the left edge of the region.
objMC | A Mathcad Region object.


Y Property

The Y property gets the zero-based coordinate of the top edge of the region, in logical document units.

Syntax

uLong = objMC.Y

Element | Description
uLong | The zero-based coordinate of the top edge of the region.
objMC | A Mathcad Region object.


Value Classes

The Value classes wrap the notion of a "value" — the right-hand-side of an assignment statement — in a Mathcad worksheet.

INumericValue class

IStringValue class

IMatrixValue class


NumericValue Class

NumericValue Interface

The NumericValue class represents all numeric values — integers, reals, and complex numbers — which can be used in a Mathcad worksheet, and contains the following properties:

Properties

  • AsString
  • Imag
  • Integer
  • Real
  • Tag


AsString Property

The AsString property returns a Mathcad value expressed as a string.

Syntax

bStr = objMC.AsString

Element | Description
bStr | The value queried, expressed as a string.
objMC | A Mathcad value object.


Imag Property

The Imag property gets or sets the imaginary part of a numeric value in a Mathcad worksheet.

Syntax

double = objMC.Imag

objMC.Imag = double

Element | Description
double | The real part of the value.
objMC | The Mathcad Numeric value object.


Integer Property

The Integer property gets or sets the real part of a numeric value in a Mathcad worksheet as an integer.

Syntax

long = objMC.Integer

objMC.Integer = long

Element | Description
long | The real part of the value, as a long integer.
objMC | A Mathcad Numeric value object.


Real Property

The Real property gets or sets the real part of a numeric value in a Mathcad worksheet.

Syntax

double = objMC.Real

objMC.Real = double

Element | Description
double | The real part of the value.
objMC | A Mathcad Numeric value object.


Type Property

The Type property gets the type associated with a Mathcad value.

Syntax

bStr = objMC.Type

Element | Description
bStr | The type of the value queried. Returns either number, string, or matrix.
objMC | A Mathcad value object.


StringValue Class

The StringValue class represents the string values which can be used in a Mathcad worksheet, and contains the following properties:

Properties

  • AsString
  • Tag
  • Value


Value Property (StringValue Class)

Value Property

The Value property gets or sets a string value in a Mathcad worksheet.

Syntax

bStr = objMC.Value

objMC.Value = bStr

Element | Description
double | A string value in a Mathcad worksheet.
objMC | A Mathcad String value object.


MatrixValue Class

The MatrixValue class is a standard OLE collection interface representing arrays, where the items are all of type variant. MatrixValue contains the following properties and methods:

Properties

  • AsString
  • Cols
  • Rows
  • Type

Methods

  • GetElement
  • SetElement


Cols Property (MatrixValue Class)

Cols Property

The Cols property gets the number of columns in a matrix.

Syntax

long = objMC.Cols

Element | Description
long | The number of columns in the matrix.
objMC | The Mathcad Matrix object.


Rows Property (MatrixValue Class)

Rows Property

The Rows property gets the number of rows in a matrix.

Syntax

long = objMC.Rows

Element | Description
long | The number or rows in the matrix.
objMC | A Mathcad Matrix object.


GetElement Method

The GetElement method retrieves the value of a specified matrix element.

VT_DISPATCH = objMC.GetElement(Row As Long, Col as Long)
Element | Description
VT_DISPATCH | A value object representing the value stored at the specified position in the matrix.
objMC | The Mathcad Matrix object.
Row | Zero-based row index of the element being retrieved.
Col | Zero-based column index of the element being retrieved.

Remarks

The GetElement method can return an error if you specify an invalid index.


SetElement Method

The SetElement method sets the value of a specified matrix element.

objMC.SetElement Row As Long, Col as Long, Value As Variant

Element | Description
objMC | The Mathcad Matrix object.
Row | Zero-based row index of the element being set.
Col | Zero-based column index of the element being set.
Value | The new element value.

Remarks

This method returns no meaningful result.

If either Row or Col is larger than the current bounds of the matrix, the matrix will be enlarged appropriately. Therefore, when populating a new matrix, it will be most efficient to set elements at the highest indecies first, so that the matrix is immediately allocated to the largest necessary size, as in the following example:

The SetElement method can return an error if you specify an invalid index.


Embedding Overview

The IMathcad interface can be used with Mathcad 7.02 and higher. IMathcad consists of four Methods, which allow you to pass data to and from a Mathcad worksheet, recalculate it, and save your calculations to a file. The IMathcad interface is used when inserting a Mathcad worksheet via the Insert OLE Object dialog or when accessing a Mathcad worksheet via a file moniker such as Visual Basic's "GetObject".

Starting in Mathcad 2001i, IMathcad was been extended with a new Worksheet property. Otherwise, the IMathcad interface remains untouched from previous versions of Mathcad.

Note: This interface is deprecated. New code should use the Worksheet class, documented in the Automation API.

Property

  • Worksheet - returns the Worksheet Class of the new Automation Interface

Methods

  • GetComplex
  • Recalculate
  • SaveAs
  • SetComplex


GetComplex Method

The GetComplex method retrieves complex data (real and imaginary parts) from Mathcad variables.

Syntax

longRet = objMC.GetComplex(Name As String, RealPart, ImagPart)

Element | Description
longRet | Return value indicating success or failure.
objMC | A Mathcad document object.
Name | A string that is one of out0, out1, out2, etc.
RealPart | A variant that receives the real part of the Mathcad document variable described by Name.
ImagPart | A variant that receives the imaginary part of the Mathcad document variable described by Name.

Remarks

When using Visual Basic, the RealPart and ImagPart variables should be declared as variants.


SetComplex method

The SetComplex method assigns complex data (real and imaginary parts) to Mathcad variable Name, where Name is one of in0, in1, in2, myVariable, etc.

Syntax

longRet = objMC.SetComplex(Name As String, RealPart, ImagPart)

Element | Description
longRet | Return value indicating success or failure.
objMC | A Mathcad document object.
Name | A string that is one of in0, in1, in2, myVariable, etc.
RealPart | A variant whose contents will be assigned to the real part of the Mathcad document variable described by Name.
ImagPart | A variant whose contents will be assigned to the imaginary part of the Mathcad document variable described by Name.

Remarks

When using Visual Basic, the RealPart and ImagPart variables should be declared as variants.


Recalculate Method (IMathcad)

Recalculate method

The Recalculate method recalculates the Mathcad document.

Syntax

longRet = objMC.Recalculate

Element | Description
longRet | Return value indicating success or failure.
objMC | A Mathcad document object.

Remarks

The Recalculate method should be invoked after passing new values to the Mathcad document via the SetComplex method. This is necessary to ensure that the contents of the worksheet, including outputs, remain consistent with the new inputs.


SaveAs Method (IMathcad)

SaveAs method

The SaveAs method saves the Mathcad document to a file.

Syntax

longRet = objMC.SaveAs(Name)

Element | Description
longRet | Return value indicating success or failure.
objMC | A Mathcad document object.
Name | The complete path name for the file. Supplying a filename only will result in a save to the current working directory.

Remarks

This method is useful for saving the contents of a Mathcad Document object that was not created from a file.


Overview of Examples

The examples that follow illustrate how you can use Mathcad's OLE Automation interface with Excel and Visual Basic 6.0. The specific steps involved differ slightly depending on the application in which you are working, but the main steps are as follows:

  • Provide a Mathcad Document OLE object with which to communicate.

  • Set up the application with the data to send to Mathcad and/or places to put the data retrieved from Mathcad.

  • Write code to specify the data to send to Mathcad and/or the data to retrieve.

Although the examples are simple, they should help you understand the basics of using Mathcad's OLE Automation interface.


Visual Basic Example

This example uses a simple Visual Basic 6.0 program to set the variable in0 in a Mathcad OLE object to a complex number, allow Mathcad to perform a calculation, and put the answer into a TextBox control.

Step 1. Add a Reference to the Mathcad object to the object browser.

  1. Choose References from the Project menu.

  2. In the list of Available References, select Mathcad.

  3. Make sure the check box to the left of Mathcad is checked and click "OK."

  4. To view Mathcad's object model, choose Object Browser from the View menu and select Mathcad in the list of available libraries.

Step 2. Design the form. For example, your form might look like this:

On the left is the Mathcad Document object within an OLE Container control. It contains statements to show the input, perform a single calculation, and display the output. On the right are textboxes to provide input and view output from the Mathcad object. There is also a CommandButton control used to submit the input to Mathcad, recalculate, and extract the output to the output TextBox controls.

Step 3. Write the code.

Private Sub cmdSubmit_Click()

Dim objMC As Object

Dim varInReal As Variant, varInImag As Variant

Dim varOutReal As Variant, varOutImag As Variant

'set a reference to the Mathcad object in the OLE container

Set objMC = OLE1.Object

'pass data to Mathcad worksheet via the SetComplex method

'getting inputs from the contents of the textboxes

'NOTE: normally you would validate inputs here prior to conversion from string values

varInReal = CDbl(txtInReal.Text)

varInImag = CDbl(txtInImag.Text)

Call objMC.SetComplex("in0", varInReal, varInImag)

'recalculate worksheet

Call objMC.Recalculate

'retrieve data from Mathcad using the GetComplex method

Call objMC.GetComplex("out0", varOutReal, varOutImag)

'assign outputs to textboxes

txtOutReal.Text = CStr(varOutReal)

txtOutImag.Text = CStr(varOutImag)

End Sub

Note:

  • See the VB projects in the SAMPLES\VBASIC folder in your Mathcad installation directory for working projects that demonstrate Mathcad's Automation interface.


Excel Example

You can use an application such as Microsoft Excel to access Mathcad's OLE Automation interface using Excel's VBA environment. The following example sets the variable in0 in a Mathcad OLE object to a complex number, allows Mathcad to perform a calculation, and puts the answer back into Excel.

Step 1. Insert an OLE object into an Excel worksheet:

  1. Choose Object from the Insert menu.

  2. Choose Mathcad Document in the New tab or choose an existing Mathcad worksheet from the Create from File tab.

  3. Click "OK."

Step 2. Set up the application so that there is data to pass to Mathcad and/or available cells to store data retrieved from Mathcad.

Step 3. Write a Visual Basic macro module:

  1. Choose Macro/Module from the Insert menu.

  2. Enter appropriate VBA code that refers to data in your worksheet and the variables in Mathcad.

Step 4. Run the macro:

  1. First, double-click on the Mathcad object in the Excel worksheet to activate the object.

  2. Run the macro from the Excel worksheet by choosing Macro/Run from the Tools menu.

For example, the following is an Excel worksheet communicating with Mathcad through a VBA macro. The data stored in cells I7 through J8 are passed into the Mathcad variable in0. Mathcad performs a calculation (in this case, it trivially adds 1 to the values, but you can use Mathcad to perform any calculation you can do in Mathcad). The results stored in the Mathcad variable out0 are passed into the cells I12 through J13.

TheVBA macro looks like this:

Sub UpdateWorksheet()

Dim MathcadObject As Object

Dim outRe, outIm As Variant

Dim inRe, inIm As Variant

' Set a reference to the Mathcad object on the shee

Set MathcadObject = ActiveSheet.OLEObjects(1).Object

' Read in values to be passed from Excel to Mathcad

inRe = ActiveSheet.Range("I7:I8").Value

inIm = ActiveSheet.Range("J7:J8").Value

' Send the values over to Mathcad, assign them to variable in0,

' recalculate, and read the results from out0 back into Excel

Call MathcadObject.SetComplex("in0", inRe, inIm)

Call MathcadObject.Recalculate

Call MathcadObject.GetComplex("out0", outRe, outIm)

' Place the result values into the chosen Excel cells

ActiveSheet.Range("I12:I13").Value = outRe

ActiveSheet.Range("J12:J13").Value = outIm

End Sub

Note that in order to pass real data, you should have cell(s) containing zeros for the imaginary part.

Note:

  • See SAMPLES\EXCEL\TRAJECT.XLS in your Mathcad installation directory for a working example with documented code.


MCM File

File format for exported scripted controls.

Mathcad uses an MCM file to save a customized control for reuse in other Mathcad worksheets. MCM files consist of two parts:

  • The script associated with the control, and
  • The customized properties of the control.

By exporting a control to an MCM file, you create a new component available in the Component Wizard the next time you access it. In addition, the MCM file is portable, and can be distributed without a Mathcad worksheet. To use the control on a new machine, simply double-click on the MCM file, and it will automatically be registered and available in the Component Wizard.

To remove an MCM file from your system:

  1. Open the Start menu in Windows, and click Run.

  2. Click the Browse button. Navigate to your Mathcad program directory, and select the file mcmreg.exe. Click "OK".

  3. In the Run dialog, add the following command-line arguments:
    /u mcm\control.mcm, where control.mcm is the MCM file you want to delete; in example, it is located in the mcm directory of your Mathcad installation. The "/u" removes information on the MCM file from the Windows Registry.

  4. Once you have unregistered the component, it will no longer appear in the Component Wizard and you can delete the MCM file from your system.